Hangfire单例重复出现的工作

时间:2015-06-11 17:31:57

标签: c# asp.net-mvc hangfire

我正在尝试使用Hangfire在后台运行定期作业,轮询来自其他网站的数据,问题是如果上一个作业仍在运行,我不希望重复作业运行。

我已经阅读了文档,但似乎无法找到答案。有没有办法让一个每10分钟运行一次的定期工作,但如果之前的任务还没有完成则会跳过?

public void Configuration(IAppBuilder app)
{
    app.MapSignalR();

    // Hangfire
    GlobalConfiguration.Configuration
        .UseSqlServerStorage("DatabaseContext");

    app.UseHangfireDashboard();
    app.UseHangfireServer();

    RecurringJob.AddOrUpdate("site-parser", () => SiteParserService.RunAll(), Cron.Minutely, TimeZoneInfo.Utc);

    ConfigureAuth(app);
}

2 个答案:

答案 0 :(得分:4)

你可以使用; 作业方法的[DisableConcurrentExecution(10 * 60)]属性。

您可以在此处找到有关此属性的信息: http://odinserj.net/2014/05/21/hangfire-0.8.2-released/

答案 1 :(得分:0)

我的解决方案:

namespace MyNameSpace
{
    public delegate void LockWrapperDelegateVoid();

    /* Job Locker. One job can work at current moment. Different jobs can work parallel */
    public static class JobLocker
    {
        private static readonly ConcurrentDictionary<string, bool> _locks = new ConcurrentDictionary<string, bool>();

        private static string LocksTryAdd(string lockerName)
        {
            if (string.IsNullOrEmpty(lockerName))  // lock by procedure's name (in this example = "JobProcedure")
            {
                lockerName = new StackFrame(2).GetMethod().Name;
            }
            if (!_locks.ContainsKey(lockerName))
            {
                _locks.TryAdd(lockerName, false);
            }
            return lockerName;
        }

        public static void LockWrapperVoid(string lockerName, LockWrapperDelegateVoid lockWrapperDelegateVoid)
        {
            lockerName = LocksTryAdd(lockerName);
            if (!_locks[lockerName])
            {
                _locks[lockerName] = true;
                try
                {
                    lockWrapperDelegateVoid();
                }
                finally
                {
                    _locks[lockerName] = false;
                }
            }
        }
    }
}

// USING

// JOB description
TryAddOrUpdateJob("JOB TITLE", () => JobManager.JobProcedure(), "* * * * *", TimeZoneInfo.Utc, "queueDefault");  // every one minute


public static void JobProcedure()
{
    // very important. You can use "BlockArea" instead null and use one area if several jobs depend each other
    // if null - area will have name like as the procedure ("JobProcedure")
    JobLocker.LockWrapperVoid(null, () =>  
    {
        //your code here
        System.Threading.Thread.Sleep(2 * 1000 * 60); // timeout - 2 minutes
    });
}