我有服务。我想验证,如果现在的日期等于某个日期,将做某事(将发送邮件)。
如何使用 Windows 任务计划程序或其他方式来处理每年在同一天(例如 11 月 15 日)触发的事件
请给我使用与某个日期相关的 Windows 任务计划程序(类、参数、属性、方法)的示例。我可以使用计时器吗?
我有服务。我想验证,如果现在的日期等于某个日期,将做某事(将发送邮件)。
如何使用 Windows 任务计划程序或其他方式来处理每年在同一天(例如 11 月 15 日)触发的事件
请给我使用与某个日期相关的 Windows 任务计划程序(类、参数、属性、方法)的示例。我可以使用计时器吗?
我看到两个选项
在第一个选项中,您不需要计时器,因为 Windows 正在为您管理时钟轮询。在第二个选项中,计时器是合适的。制作多长时间取决于您!
编辑-一些极其琐碎的代码示例
选项 1.调用 Windows 任务计划程序可执行文件并使用命令行设置您的任务 - > 在 Windows 任务计划程序 C# 中计划任务
在命令提示符下键入schtasks /CREATE /?
让您开始!
选项 2。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimeToTarget
{
class Program
{
static TimeSpan m_TimeToTarget = default(TimeSpan);
static void Main(string[] args)
{
//maybe you can load this from file or take it from the commandline as commented below
//string cmd = Environment.GetCommandLineArgs();
DateTime now = DateTime.Now;
DateTime target = new DateTime(now.Year, 11, 15); //November 15th. Use todays year.
//we want to set a timer for the next occurance of Nov 15th.
if (DateTime.Now > target)
{
//increment the year because today is after Nov 15th but before new year.
target = new DateTime(now.Year, 11, 15).AddYears(1);
}
m_TimeToTarget = target.Subtract(now);
//kick off a timer to wait for the event
SetTimer(m_TimeToTarget);
Console.ReadLine(); //console needs to continue running to keep the process alive as timer runs in background thread
}
private static void SetTimer(TimeSpan timeToTarget)
{
System.Threading.Timer t = new System.Threading.Timer(DoWork, null, Convert.ToInt32(timeToTarget.TotalMilliseconds),
System.Threading.Timeout.Infinite); //dont repeat, we want the time to end when it start our work
}
private static void DoWork(object state)
{
//Do you work here!
//restart the time
SetTimer(m_TimeToTarget);
}
}
}
你有几个选择:
您可以每天安排您的活动,但在事件处理程序内部只需检查当前日期。如果当前日期看起来不错(例如 11 月 15 日),则继续执行有用的任务。
您可以提前几年安排一些一次性活动。
您可以创建在某些特定事件上触发的计划(任务计划程序有这样的选项)。然后外部的东西将不得不在 11 月 15 日记录此类特定事件。
创建您自己的 Windows 服务,该服务始终运行并将决定何时开始您的任务。