【问题标题】:C# Schedule a Function using Quartz.net (or alternatives)C# 使用 Quartz.net(或替代方案)调度函数
【发布时间】: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


【解决方案1】:

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

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);

    }

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

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

        await TestScheduler();

        Console.ReadKey();
    }

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

希望对你有帮助。

【讨论】:

  • 很好的例子,与其他众多的例子和文档不同,这让我启动并运行。
猜你喜欢
  • 2018-10-16
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多