c# - 安排 Windows 服务在每天凌晨 3:00 运行
问题描述
protected override void OnStart(string[] args)
{
aTimer = new Timer();
var timer = System.Configuration.ConfigurationManager.AppSettings["Timer"].ToString(); //Appconfig "03:00"
var date = DateTime.Now;
DateTime scheduled = DateTime.ParseExact(timer, "HH:mm",
CultureInfo.InvariantCulture);
if (date > scheduled) scheduled = scheduled.AddDays(1);
var test = scheduled.Subtract(date).TotalMinutes;
aTimer.Interval = test;
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Enabled = true;
aTimer.AutoReset = false;
}
上面的代码在启动时第一次运行,然后即使间隔设置为每天凌晨 3:00 运行,它也不会再次运行。
更新: 效果很好。我想知道如果我将计时器设置为每 1 秒运行一次,它是否有可能与每个事件重叠。在开始新的事件之前是否等待事件结束?
解决方案
AutoReset 应该为 true,以便多次引发事件。你为什么把它设置为假?
请参阅https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer.autoreset?view=net-5
但更好的是使用windows scheduler。如果重新启动或重新启动/停止服务,您的代码将无济于事。
推荐阅读
- css - MUI - 如何在特定样式的组件中使用伪类
- r - 在r中解析多级json文件
- r - 创建配方并动态传递列名
- python - 取连续行直到特定值熊猫数据框
- email - iCal Outlook 电子邮件兼容性问题
- c++ - 使用 llvm-13 构建(OrcV2)Jit 编译器时如何解析驻留在当前会话中的符号?
- sql-server - 当主表具有 (Identity (1, 1)) 时,错误“引用表中没有主键或候选键”
- c# - List 计算 WhereNot 的扩展方法
- kotlin - 为什么我不能在 Kotlins 正则表达式结果序列上使用 map
- python - 根据特定列 Pandas 的连续值合并 df 的行