I would like to have an event triggered in my app which runs continuously during the day at a certain time, say at 4:00pm. I thought about running the timer every second and
Echo to Dan's solution, using Timercallback is a quick and neat solution. Inside the method you want to schedule a task or subroutine to be run, use the following:
t = New Timer(Sub()
'method call or code here'
End Sub, Nothing, 400, Timeout.Infinite)
use of 'Timeout.Infinite' will ensure the callback will be executed only once after 400ms. I am using VB.Net.
Taking VoteCoffees lead, here is a compact event based solution:
public class DailyTrigger
{
readonly TimeSpan triggerHour;
public DailyTrigger(int hour, int minute = 0, int second = 0)
{
triggerHour = new TimeSpan(hour, minute, second);
InitiateAsync();
}
async void InitiateAsync()
{
while (true)
{
var triggerTime = DateTime.Today + triggerHour - DateTime.Now;
if (triggerTime < TimeSpan.Zero)
triggerTime = triggerTime.Add(new TimeSpan(24,0,0));
await Task.Delay(triggerTime);
OnTimeTriggered?.Invoke();
}
}
public event Action OnTimeTriggered;
}
Consumer:`
void Main()
{
var trigger = new DailyTrigger(16); // every day at 4:00pm
trigger.OnTimeTriggered += () =>
{
// Whatever
};
Console.ReadKey();
}
Task scheduler is a better option, and it can be easily used in C#, http://taskscheduler.codeplex.com/