0
votes

I'm working on a project which needs to do something every 24h. I have a timer for that, but when i start the program i want it to delay the timer once så im sure it runs during the night.

The timer :

timeForFitbitUpdate = 86400000; // Setting 24 hours of intervals
Timer aTimer = new Timer(10);
aTimer.Elapsed += new ElapsedEventHandler(RunEvent);
aTimer.Interval = timeForFitbitUpdate;
aTimer.Enabled = true;

I have tried this code:

int delayTime = CalculateDelay();
var connectionString = ConfigurationManager.ConnectionStrings["VRT"].ConnectionString;
FitbitDataSave dataSave = new FitbitDataSave(connectionString);
await Task.Delay(delayTime);
dataSave.DoTimedWork();

but with other hardcoded miliseconds both in timer and the delay.. The delay was set to 5 minutes and timer to 5 minutes and it took the first time 10 minutes and after that 11 minutes and so on..

If any one have any ideas pls share thnx :)

1
You can use task to delay the start of the timer like : Task.Factory.StartNew( () => { Stopwatch sw = new Stopwatch(); sw.Start(); while(sw.ElapsedMilliseconds != delayTime){} aTimer.Enabled = true; }); - Mateusz
@m.rogalski, please don't recommend CPU intensive polling (or polling at all), we have Task.Delay()/Thread.Sleep() for this (see this answer). - Sinatr
@Sinatr It;s up to him which method he will use to wait for delay. I'm just giving simpliest and readable example - Mateusz
If it is something that must be done once a day, i would go with a scheduled task... - Pikoh

1 Answers

0
votes

I would probably set your interval to CalculateDelay(); on start-up.

Then as part of your ElapsedEventHandler, change your interval to your 24 hour setting.