Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 00:20
- 00:40
- 01:00
- 01:20
- 01:40
- int CalculateTimerInterval(int minute)
- {
- if (minute <= 0)
- minute = 60;
- DateTime now = DateTime.Now;
- DateTime future = now.AddMinutes((minute - (now.Minute % minute))).AddSeconds(now.Second * -1).AddMilliseconds(now.Millisecond * -1);
- TimeSpan interval = future - now;
- return (int)interval.TotalMilliseconds;
- }
- static System.Windows.Forms.Timer t;
- const int CHECK_INTERVAL = 20;
- static void Main()
- {
- t = new System.Windows.Forms.Timer();
- t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
- t.Tick += new EventHandler(t_Tick);
- t.Start();
- }
- static void t_Tick(object sender, EventArgs e)
- {
- t.Interval = CalculateTimerInterval(CHECK_INTERVAL);
- }
- int minutes = DateTime.Now.Minute;
- int adjust = 10 - (minutes % 10);
- timer.Interval = adjust * 60;
- public Form1()
- {
- InitializeComponent();
- //some fake data, obviously you would have your own.
- DateTime someStart = DateTime.Now.AddMinutes(1);
- TimeSpan someInterval = TimeSpan.FromMinutes(2);
- //sample call
- StartTimer(someStart,someInterval,doSomething);
- }
- //just a fake function to call
- private bool doSomething()
- {
- DialogResult keepGoing = MessageBox.Show("Hey, I did something! Keep Going?","Something!",MessageBoxButtons.YesNo);
- return (keepGoing == DialogResult.Yes);
- }
- //The following is the actual guts.. and can be transplanted to an actual class.
- private delegate void voidFunc<P1,P2,P3>(P1 p1,P2 p2,P3 p3);
- public void StartTimer(DateTime startTime, TimeSpan interval, Func<bool> action)
- {
- voidFunc<DateTime,TimeSpan,Func<bool>> Timer = TimedThread;
- Timer.BeginInvoke(startTime,interval,action,null,null);
- }
- private void TimedThread(DateTime startTime, TimeSpan interval, Func<bool> action)
- {
- bool keepRunning = true;
- DateTime NextExecute = startTime;
- while(keepRunning)
- {
- if (DateTime.Now > NextExecute)
- {
- keepRunning = action.Invoke();
- NextExecute = NextExecute.Add(interval);
- }
- //could parameterize resolution.
- Thread.Sleep(1000);
- }
- }
- private Timer _timer;
- private Int32 _hours = 0;
- private Int32 _runAt = 3;
- protected override void OnStart(string[] args)
- {
- _hours = (24 - (DateTime.Now.Hour + 1)) + _runAt;
- _timer = new Timer();
- _timer.Interval = _hours * 60 * 60 * 1000;
- _timer.Elapsed += new ElapsedEventHandler(Tick);
- _timer.Start();
- }
- void Tick(object sender, ElapsedEventArgs e)
- {
- if (_hours != 24)
- {
- _hours = 24;
- _timer.Interval = _hours * 60 * 60 * 1000;
- }
- RunImport();
- }
Add Comment
Please, Sign In to add comment