0

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 :)

Yael
  • 1,566
  • 3
  • 18
  • 25
  • 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; });` – mrogal.ski Nov 29 '16 at 11:23
  • 2
    @m.rogalski, please don't recommend CPU intensive polling (or polling at all), we have `Task.Delay()`/`Thread.Sleep()` for this (see [this](http://stackoverflow.com/a/5743843/1997232) answer). – Sinatr Nov 29 '16 at 11:24
  • @Sinatr It;s up to him which method he will use to wait for delay. I'm just giving simpliest and readable example – mrogal.ski Nov 29 '16 at 11:26
  • If it is something that must be done once a day, i would go with a scheduled task... – Pikoh Nov 29 '16 at 11:28

1 Answers1

0

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.

McGaz
  • 1,354
  • 1
  • 13
  • 22