https://social.technet.microsoft.com/wiki/contents/articles/37252.c-timer-schedule-a-task.aspx?Sort=MostRecent&PageIndex=1
using System;
using System.Timers;
namespace ScheduleTimer
{
class Program
{
static Timer timer;
static void Main(string[] args)
{
schedule_Timer();
Console.ReadLine();
}
static void schedule_Timer()
{
Console.WriteLine("### Timer Started ###");
DateTime nowTime = DateTime.Now;
DateTime scheduledTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 8, 42, 0, 0);
if (nowTime > scheduledTime)
{
scheduledTime = scheduledTime.AddDays(1);
}
double tickTime = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
timer = new Timer(tickTime);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Console.WriteLine("### Timer Stopped ### \n");
timer.Stop();
Console.WriteLine("### Scheduled Task Started ### \n\n");
Console.WriteLine("Hello World!!! - Performing scheduled task\n");
Console.WriteLine("### Task Finished ### \n\n");
schedule_Timer();
}
}
}
封装好的类:
using System;
using System.Windows.Forms;
using System.Timers;
using System.Diagnostics;
namespace ScheduleTimer
{
class ScheduleTimer
{
System.Timers.Timer timer = null;
public TimeSpan Start { get; set; }
public TimeSpan End { get; set; }
public int Interval { get; set; }
private string Command { get; set; }
private string Arguments {get; set; }
DateTime scheduledTime;
public void Init(TimeSpan start, TimeSpan end, int interval_seconds, string command, string Arugments)
{
Start = start;
End = end;
Interval = interval_seconds;
Command = command;
scheduledTime = DateTime.Today + start;
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(OnTimer);
}
public void Stop()
{
if (timer != null) timer.Stop();
}
public void run()
{
if (timer == null) return;
timer.Stop();
while (scheduledTime < DateTime.Now) {
scheduledTime = scheduledTime.AddSeconds(Interval);
}
timer.Interval = (double)(scheduledTime - DateTime.Now).TotalMilliseconds;
timer.Start();
scheduledTime = scheduledTime.AddSeconds(Interval);
}
void OnTimer(object sender, ElapsedEventArgs e)
{
timer.Stop();
DateTime now = DateTime.Now;
if (now < now.Date + Start)
{
scheduledTime = now.Date + Start;
}
else if (now <= now.Date + End) {
Process push = new Process();
push.StartInfo.UseShellExecute = false;
push.StartInfo.FileName = Command;
push.StartInfo.CreateNoWindow = true;
push.StartInfo.WorkingDirectory = Application.StartupPath;
push.StartInfo.Arguments = Arguments;
push.Start();
}
else {
}
run();
}
}
}
用法:
ScheduleTimer.ScheduleTimer st = new ScheduleTimer.ScheduleTimer();
TimeSpan Start = Convert.ToDateTime("08:00:00").TimeOfDay;
st.Init(new TimeSpan(08, 0, 0), new TimeSpan(18, 00, 00), 60, "cmd /c", "dir");
st.run();