I need help to write a windows service with a timer that can call 3 different function(events) in 3 different times every day.
Some code example please. Thank you.
private System.Timers.Timer timer;
protected override void OnStart(string[] args)
{
this.timer1 = new System.Timers.Timer(60000);
this.timer1.AutoReset = true;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
this.timer1.Start();
}
private DateTime _lastRun1 = DateTime.Now.AddDays(-1);
private DateTime _lastRun2 = DateTime.Now.AddDays(-1);
private DateTime _lastRun3 = DateTime.Now.AddDays(-1);
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_lastRun.Date < DateTime.Now.Date && DateTime.Now.Hour == 13)
{
//call functionX
DateTime _lastRun1 = DateTime.Now.AddDays(1);
}
if (_lastRun.Date < DateTime.Now.Date && DateTime.Now.Hour == 14)
{
//call functionY
DateTime _lastRun2 = DateTime.Now.AddDays(1);
}
if (_lastRun.Date < DateTime.Now.Date && DateTime.Now.Hour == 16)
{
//call functionXY
DateTime _lastRun3 = DateTime.Now.AddDays(1);
}
}
Why not just write 3 distinct applications and let the Windows task scheduler execute them at the appropriate times? This will probably be a lot easier than trying to get your own scheduling logic right, which can often be more complicated than you'd expect.
Related
I want to launch a method in a program every 12 hours.
What do I have to do ?
Do I have to use a Timer to doing this ?
I have this code :
aTimer = new System.Timers.Timer(1000); //One second, (use less to add precision, use more to consume less processor time
int lastHour = DateTime.Now.Hour;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Start();
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if(lastHour < DateTime.Now.Hour || (lastHour == 23 && DateTime.Now.Hour == 0))
{
lastHour = DateTime.Now.Hour;
YourImportantMethod(); // Call The method with your important staff..
}
}
Can I adapt it to launch my program every 12 hours ?
A simple solution with async/await:
private static async void RepeatedAction()
{
TimeSpan delay = TimeSpan.FromHours(12);
while (true)
{
await Task.Delay(delay);
YourImportantMethod();
}
}
Use System.Threading.Timer
var start = TimeSpan.Zero;
var period = TimeSpan.FromHours(12);
var timer = new System.Threading.Timer((e) =>
{
YourImportantMethod();
}, null, start, period);
You can use Cron Jobs for this situation
Here is url check and implement. In corn job you can set when your program run
The label must change when the page loads. I don't get any errors but the label stays what I named the label.
my code:
private void Form1_Load(object sender, EventArgs e)
{
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 20;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
I tried to put timelbl.Text = "Oggend" in aswell but it didn't work.
Oggend means Morning, Middag means Day and aand means Night
Using variables for "times of day" is redundant. You may keep them if that's what you want, but it won't be the best thing to do.
private void Form1_Load(object sender, EventArgs e) {
DateTime curTime = DateTime.Now;
int one = 5; //times of day
int two = 12;
int three = 8;
string ogg = "Oggend";
string mid = "Middag";
string aan = "Aand";
if (curTime.Hour >= one && curTime.Hour <= two)
{
timelbl.Text = ogg;
}
else if (curTime.Hour > two && curTime.Hour < three)
{
timelbl.Text = mid;
}
else
{
timelbl.Text = aan;
}
}
Your code seems to be fine. You just need to make sure that page load event fires so that the variable value assigned to the label. You should add a break point in page load event and ensure that the event fires properly.
I was trying to Code some simple scheduled Task, which should be executed every full minute (aka when seconds are at 0) but somehow it got messed up. Instead of only doing its job once, it does it over and over as long as the seconds are at 0.
I tried to prevent that by using a bool indicator, but that didnt work.
Hier is my Code example:
static void Main()
{
bool now = true;
while (true)
{
if (DateTime.Now.Second == 0 && now == true)
{
Console.WriteLine("now is: " + DateTime.Now);
now = false;
}
else
{
now = true;
}
}
}
I would prefer to not use sleeps or delays and would like to schedule it by actual time.
Is there an easy way to solve this?
Keep track of your current time and your next run time by changing your code to something like
static void Main(string[] args)
{
var now = DateTime.Now;
var nextRunTime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0).AddMinutes(1);
while (true)
{
var currentTime = DateTime.Now;
if (currentTime >= nextRunTime)
{
Console.WriteLine(currentTime);
nextRunTime = nextRunTime.AddMinutes(1);
}
}
}
I have an Windows Application which uses timer like in the screen:
timer it's used to run a method every X minutes between 08:00:00 (Start Time) and 21:00:00 (Stop Time)
In the screen:
Next download Start at: shows what time the next run will occur
Time Left: shows the remaining time until next run will occur
Download Interval: time span between two runs
The method runs when the Next download Start = Current Time.
My issue is that event that the application is open and runs, the timer just stops after a while.
Any ideas why this happens, is this normal or am I doing something wrong in my code (i can post it if needed but now I was just asking to see if it's normal)?
Is there a way to prevent it or shell I create a checker and check his status regularly?
Thanks in advance for your support!
private System.Windows.Forms.Timer timerFrequency = new System.Windows.Forms.Timer();
public void LoadGeneraInfoPanel()
{
timerFrequency.Interval = 1000;
timerFrequency.Enabled = true;
this.timerFrequency.Tick += new System.EventHandler(this.timerFrequency_Tick);
timerFrequency.Start();
}
private void timerFrequency_Tick(object sender, EventArgs e)
{
txtGICurrTime.Text = DateTime.Now.ToString("HH:mm:ss");
if (drSystemParam["Auto"].ToString() == "True" && timerFrequency.Enabled)
{
if (txtGIFrequency.Text.ToString() != string.Empty && txtGIStopTime.Text.ToString() != string.Empty && txtGIStartTime.Text.ToString() != string.Empty)
{
int iHours = Convert.ToInt32(txtGIFrequency.Text.Substring(0, 2));
int iMinutes = Convert.ToInt32(txtGIFrequency.Text.Substring(3, 2));
int iSeconds = Convert.ToInt32(txtGIFrequency.Text.Substring(6, 2));
DateTime dCurrStartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStartTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStartTime.Text.Substring(6, 2)));
DateTime dCurrStopTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt32(txtGIStopTime.Text.Substring(0, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(3, 2)), Convert.ToInt32(txtGIStopTime.Text.Substring(6, 2)));
DateTime dCurrStartDownloadTime = dCurrStartTime;
for (int j = 0; dCurrStartDownloadTime < DateTime.Now & dCurrStartDownloadTime <= dCurrStopTime; j++)
dCurrStartDownloadTime = dCurrStartDownloadTime.AddHours(iHours).AddMinutes(iMinutes).AddSeconds(iSeconds);
var result = dCurrStartDownloadTime;
if (DateTime.Now > dCurrStartTime && DateTime.Now < dCurrStopTime.AddHours(-iHours).AddMinutes(-iMinutes).AddSeconds(-iSeconds))
{
if (txtNextDownloadTime.Text == String.Empty)
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
if (DateTime.Now.ToString("HH:mm:ss") == txtNextDownloadTime.Text)
{
timerFrequency.Stop();
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
Thread.Sleep(800);
timerFrequency.Enabled = true;
timerFrequency.Start();
btnEecuteMethod_Click(sender, e);
}
}
else
{
result = dCurrStartTime.AddDays(1);
txtNextDownloadTime.Text = result.ToString("HH:mm:ss");
TimeSpan diff = result - DateTime.Now.AddSeconds(-1);
txtGITimeLeft.Text = string.Format("{0}:{1}:{2}", diff.Hours.ToString().PadLeft(2, '0'), diff.Minutes.ToString().PadLeft(2, '0'), diff.Seconds.ToString().PadLeft(2, '0'));
}
}
else
{
timerFrequency.Enabled = false;
timerFrequency.Stop();
}
}
}
Want to do a loop of picture slideshow to start from a specific time and then to end at another specific time.
Also, how to set the DateTime picker to select minutes/hours?
//Under start button
if (rbtnDateTime.Checked == true)
{
DateTime startDate = dateTimePicker1.Value.Date;
DateTime stopDate = dateTimePicker2.Value.Date;
//Given time interval in seconds
if (mtxtSlideShowInterval.Text != "")
{
int interval = Convert.ToInt16(mtxtSlideShowInterval.Text);
while ((startDate = startDate.AddSeconds(interval)) <= stopDate)
{
timerSlideShow.Enabled = true;
timerSlideShow.Start();
}
timerSlideShow.Stop();
timerSlideShow.Enabled = false;
}
}
//Under timer_tick event
//Infinite Loop
else
{
if (listBoxPicturesInAlbum.SelectedIndex ==listBoxPicturesInAlbum.Items.Count - 1)
{
listBoxPicturesInAlbum.SelectedIndex = 0;
}
else
{
listBoxPicturesInAlbum.SelectedIndex++;
}
}
I would be rid of the while loop you have, and take a few steps.
First, you'll need a field to mark your current index:
int currentImageIndex = 0;
Second, you'll set your timer.Interval.
timer.Interval = int.Parse(mtxtSlideShowInterval.Text) * 1000;
Third, your timer_tick can include something like this:
if (DateTime.Now < dateTimePicker2.Value.Date)
{
listBoxPicturesInAlbum.SelectedIndex = currentImageIndex;
pictureBox.Image = Image.FromFile((string)listBoxPicturesInAlbum.SelectedValue);
currentImageIndex = (currentImageIndex + 1) % listBoxPicturesInAlbum.Items.Count;
}