【问题标题】:Is there a way to force Hangfire to execute the code again every time?有没有办法强制 Hangfire 每次都再次执行代码?
【发布时间】:2019-02-04 16:54:00
【问题描述】:

我正在尝试评估 Hangfire 作为我最新项目的潜在任务调度解决方案。

在处理重复性任务时,我注意到当我尝试控制台写入当前时间时,每次都会将相同的时间写入控制台。

有人可以告诉我如何强制hangfire在每次运行时重新执行任务吗?谷歌没有帮助,可能是因为我找不到合适的词来搜索。

“更新系统信息”任务这样就没用了。

我的代码:

using System;
using System.Globalization;
using Hangfire;
using Microsoft.Owin.Hosting;

namespace HangfireTests
{
    public class HangfireTests
    {
        public HangfireTests()
        {
        }

        public void Start()
        {
            WebApp.Start<Startup>("http://localhost:8888");
            Console.WriteLine("Server started... press any key to shut down");

            RecurringJob.AddOrUpdate("systeminfo",
                () => Console.WriteLine($"updating system information {GetTime()}"), Cron.Minutely);
            RecurringJob.AddOrUpdate("checktask",
                () => Console.WriteLine($"checking tasks {GetTime()}"), Cron.Minutely);
        }

        public static string GetTime()
        {
            return DateTime.Now.ToString(CultureInfo.InvariantCulture);
        }

        public void Stop()
        {
        }
    }
}

这是我的示例的控制台输出:

【问题讨论】:

  • 使用“Cron.Minutely”,您的重复作业将每分钟自动执行一次。 “每次运行时重新执行任务”是什么意思?
  • 重新执行,让“GetTime”函数得到实际时间,而不是任务创建的时间

标签: c# hangfire


【解决方案1】:

如果您将 GetTime 函数而不是 WriteLine 加入队列,它将在执行时进行评估。这将为您提供执行作业的时间。

using System;
using System.Globalization;
using Hangfire;
using Microsoft.Owin.Hosting;

namespace HangfireTests
{
    public class HangfireTests
    {
        public HangfireTests()
        {
        }

        public void Start()
        {
            WebApp.Start<Startup>("http://localhost:8888");
            Console.WriteLine("Server started... press any key to shut down");

        RecurringJob.AddOrUpdate("systeminfo",
            () => GetTime(), Cron.Minutely);
            RecurringJob.AddOrUpdate("checktask",
            () => GetTime(), Cron.Minutely);
    }

        public static string GetTime()
        {
            var now = DateTime.Now.ToString(CultureInfo.InvariantCulture);
            Console.WriteLine(now);
            return now;
        }

        public void Stop()
        {
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-12-03
    • 2022-01-18
    • 1970-01-01
    • 2018-03-21
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多