gpt4 book ai didi

C# 使用 Quartz.net(或替代方案)安排函数

转载 作者:太空宇宙 更新时间:2023-11-03 14:40:05 26 4
gpt4 key购买 nike

我有一个 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();
}
}

这是错误的

(Error CS0738 'SimpleJob' does not implement interface member 'IJob.Execute(IJobExecutionContext)'. 'SimpleJob.Execute(IJobExecutionContext)' cannot implement 'IJob.Execute(IJobExecutionContext)' because it does not have the matching return type of 'Task'.)

但这不是:

public Task Execute(IJobExecutionContext context)
{
throw new NotImplementedException();
}

有人可以为初学者提供一个通过 Quartz.net 安排的工作的当前工作示例吗?或者在 C# 服务中使用比 Quartz.net 更优雅的方法?

最佳答案

首先我们需要实现一个作业实现。例如:

internal class TestJob : IJob
{
public Task Execute(IJobExecutionContext context)
{

Console.WriteLine("Job started");
return Task.CompletedTask;
}
}

现在我们需要编写一个方法来返回 Quartz 的调度器:

    static async Task TestScheduler()
{
// construct a scheduler factory
NameValueCollection props = new NameValueCollection
{
{ "quartz.serializer.type", "binary" }
};
StdSchedulerFactory factory = new StdSchedulerFactory(props);

// get a scheduler
IScheduler sched = await factory.GetScheduler();
await sched.Start();

// define the job and tie it to our HelloJob class
IJobDetail job = JobBuilder.Create<TestJob>()
.WithIdentity("myJob", "group1")
.Build();

// Trigger the job to run now, and then every 40 seconds
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("myTrigger", "group1")
.StartNow()
.WithSimpleSchedule(x => x
.WithIntervalInMinutes(1)
.RepeatForever())
.Build();

await sched.ScheduleJob(job, trigger);

}

在程序的主要方法中,我们需要编写以下代码:

    static async Task Main()
{
Console.WriteLine("Test Scheduler started");

await TestScheduler();

Console.ReadKey();
}

现在这将在每分钟后继续执行。

希望对您有所帮助。

关于C# 使用 Quartz.net(或替代方案)安排函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57432088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com