/// <summary> /// Ticks every second. /// </summary> /// <param name="state">The state.</param> private static void Tick(object state) { ScheduledFunction scheduledFunction = state as ScheduledFunction; if (scheduledFunction == null) { return; } // Check we're still due. if (scheduledFunction.NextExecutionDue <= DateTime.Now) { scheduledFunction.ExecuteNow(); } SetTimer(scheduledFunction); }
/// <summary> /// Adds the specified schedule. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="schedule">The schedule.</param> /// <param name="function">The function.</param> /// <param name="startAfter">The date time to start after.</param> /// <param name="maximumHistory">The maximum history.</param> /// <param name="enabled">if set to <c>true</c> then the scheduled function is enabled.</param> /// <param name="executeImmediately">if set to <c>true</c> executes the function immediately.</param> /// <returns>The scheduled function.</returns> public static ScheduledFunction <TResult> Add <TResult>(Schedule schedule, Func <ScheduledFunction <TResult>, TResult> function, DateTime?startAfter = null, int maximumHistory = ScheduledFunction.DefaultMaximumHistory, bool enabled = true, bool executeImmediately = false) { ScheduledFunction <TResult> scheduledFunction = new ScheduledFunction <TResult>( schedule, function, startAfter ?? DateTime.Now, maximumHistory); // If we need to execute, do so now. if (executeImmediately) { scheduledFunction.ExecuteNow(); } // Don't add a scheduled function that is never due DateTime nextDue = scheduledFunction.NextExecutionDue; // Check if we're ever due if (nextDue == DateTime.MaxValue) { return(scheduledFunction); } Timer timer = enabled ? new Timer(Tick, scheduledFunction, Timeout.Infinite, Timeout.Infinite) : null; _timers.AddOrUpdate(scheduledFunction, timer, (sf, t) => timer); if (enabled) { SetTimer(scheduledFunction); } return(scheduledFunction); }