【问题标题】:Fire Job only one time at specific date and time在特定日期和时间仅解雇一次工作
【发布时间】:2017-08-23 15:28:03
【问题描述】:

我有 Job 的代码 - 只需将信息记录到数据库

 public class Job : IJob 
    { 
        private static readonly log4net.ILog log = 
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod( ).DeclaringType); 
        #region IJob Members 
        public void Execute(IJobExecutionContext context) 
        { 
            // This job simply prints out its job name and the 
            // date and time that it is running 
            JobKey jobKey = context.JobDetail.Key; 
            log.InfoFormat("SimpleJob says: {0} executing at {1}", 
jobKey, DateTime.Now.ToString("r")); 
        } 
        #endregion 
    } 

我的单例调度器类

public class Scheduler 
    { 
        static Scheduler() 
        { 
            NameValueCollection properties = new 
NameValueCollection(); 
            properties["quartz.scheduler.instanceName"] = "myApp"; 
            properties["quartz.scheduler.instanceId"] = "MyApp"; 
            properties["quartz.threadPool.type"] = 
"Quartz.Simpl.SimpleThreadPool, Quartz"; 
            properties["quartz.threadPool.threadCount"] = "10"; 
            properties["quartz.threadPool.threadPriority"] = "Normal"; 
            properties["quartz.scheduler.instanceName"] = 
"TestScheduler"; 
            properties["quartz.scheduler.instanceId"] = 
"instance_one"; 
            properties["quartz.jobStore.type"] = 
"Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"; 
            properties["quartz.jobStore.useProperties"] = "true"; 
            properties["quartz.jobStore.dataSource"] = "default"; 
            properties["quartz.jobStore.tablePrefix"] = "QRTZ_"; 
            // if running MS SQL Server we need this 
            properties["quartz.jobStore.lockHandler.type"] = 
"Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; 
            properties["quartz.dataSource.default.connectionString"] = 
"Server=localhost;Database=quartzr;Uid=user;Pwd=pass"; 
            properties["quartz.dataSource.default.provider"] = 
"SqlServer-20"; 
            _schedulerFactory = new StdSchedulerFactory(properties); 
            _scheduler = _schedulerFactory.GetScheduler(); 
        } 
        public static IScheduler GetScheduler() 
        { 
            return _scheduler; 
        } 
        private static readonly ISchedulerFactory _schedulerFactory; 
        private static readonly IScheduler _scheduler; 
    } 

Global.asax 启动调度器

void Application_Start(object sender, EventArgs e) 
        { 
            Scheduler.GetScheduler().Start(); 
        } 

以及添加作业的代码

 DateTime SelectedDate = this.Calendar1.SelectedDate; 
                int hour = this.TimeSelector1.Hour; 
                int minute = this.TimeSelector1.Minute; 
                int second = this.TimeSelector1.Second; 
                // First we must get a reference to a scheduler 
                // jobs can be scheduled before sched.start() has been 
called 
                // get a "nice round" time a few seconds in the 
future... 
                DateTimeOffset startTime = DateBuilder.DateOf(hour, 
minute, second, SelectedDate.Day, SelectedDate.Month, 
SelectedDate.Year); 
                try 
                { 
                    // job1 will only fire once at date/time "ts" 
                    IJobDetail job = JobBuilder.Create<Job>() 
                        .WithIdentity("job1", "group1") 
                        .Build(); 
                    ISimpleTrigger trigger = 
(ISimpleTrigger)TriggerBuilder.Create() 
                                                                  .WithIdentity("trigger1", 
"group1") 
                                                                  .StartAt(startTime) 
                                                                  .Build(); 
                    // schedule it to run! 
                    DateTimeOffset? ft = 
Scheduler.GetScheduler().ScheduleJob(job, trigger); 
                    log.Info(job.Key + 
                             " will run at: " + ft); 
                    this.Label1.Text = "Zdarzenie dodane"; 
                } 
                catch (Exception ex) 
                { 
                    log.Error(ex.Message, ex); 
                } 

问题是作业已添加到数据库中,但它会立即触发,而不是在 我的具体时间:/ 我使用最新的库 Quartz.NET 2.0 beta 2 我的代码有问题吗?我是这个API的初学者,请帮助

【问题讨论】:

    标签: c# asp.net quartz.net


    【解决方案1】:

    Quartz.Net 期望您以 UTC 格式传递日期和时间。尝试更改此行:

    .StartAt(startTime) 
    

    .StartAt(startTime.ToUniversalTime())
    

    或者,在传入之前确保 startTime 是 UTC。

    【讨论】:

    • 这如何与通过 DailyTimeIntervalScheduleBuilder 和 StartingDailyAt 的 WithDailyTimeIntervalSchedule 一起工作?
    【解决方案2】:

    StartAt 除了DateTimeOffest
    Quartz 对此有 DateBuilder 帮助类

    var minutesToFireDouble = (futureUTCtime - DateTime.UtcNow).TotalMinutes;
                   var minutesToFire = (int)Math.Floor(minutesToFireDouble); // negative or zero value will set fire immediately
                   var timeToFire = DateBuilder.FutureDate(minutesToFire, IntervalUnit.Minute);
                   var trigger = TriggerBuilder.Create()
                                               .WithIdentity("triggerC", "groupC")
                                               .StartAt(timeToFire)
                                               .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow())
                                               .Build();
    

    【讨论】:

      【解决方案3】:

      如果您已经知道您的任务需要在什么 UTC 时间运行,您可以执行以下操作:

      目标 UTC 开始时间:2017 年 9 月 1 日中午 12 点

      如下设置你的 Quartz“StartTime”:

      var MyTaskAbcStartTime = "2017-09-01 12:00:00Z"
      .StartAt(MyTaskAbcStartTime) 
      

      有关 UTC 时间格式的参考 microsoft 文档: https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

      希望这有助于为未来的 Quartz 用户节省一些时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多