【发布时间】:2019-08-09 14:24:12
【问题描述】:
我有一个 C# 服务,我需要每周运行一次函数。
我有一个正在运行的 C# 服务,它目前每 60 秒在计时器上运行一次。 请看下面一段服务的 OnStart 函数:
// Set up a timer to trigger.
System.Timers.Timer timer = new System.Timers.Timer
{
Interval = 60000 //*1000; // 60 second
};
timer.Elapsed += delegate {
// Runs the code every 60 seconds but only triggers it if the schedule matches
Function1();
};
timer.Start();
上面的代码每 60 秒调用一次 Function1() ,如果当前的星期几和时间与计划匹配,我会在 Function1 中检查它,如果匹配,则执行函数的其余部分。 虽然这确实有效,但它并不是 IMO 最优雅的方式。
我曾尝试使用 Quartz.net,因为它看起来很有希望,但是当我使用在线提供的所有示例(大约 7 年前在 2012 年回答的问题)时,它在 Visual Studio 中显示为错误:
using System;
using Quartz;
public class SimpleJob : IJob
{
public void Execute(IJobExecutionContext context)
{
throw new NotImplementedException();
}
}
这是错误的
(错误 CS0738 'SimpleJob' 没有实现接口成员 'IJob.Execute(IJobExecutionContext)'。'SimpleJob.Execute(IJobExecutionContext)' 无法实现 'IJob.Execute(IJobExecutionContext)' 因为它没有匹配的返回类型的“任务”。)
但这不是:
public Task Execute(IJobExecutionContext context)
{
throw new NotImplementedException();
}
有人可以给出一个通过 Quartz.net 为初学者安排的工作的当前工作示例吗? 或者在 C# 服务中使用 Quartz.net 之外的其他优雅方法?
【问题讨论】:
-
public Task Execute(IJobExecutionContext context)是否有效?
标签: c# quartz.net