public void Execute_a_job() { // Arrange // - Add a job into the test scheduler IScheduler sched = GetTestScheduler(); JobDetail job = new JobDetail("TestJob", "TestGroup", typeof(Quartz.Job.NoOpJob)); sched.AddJob(job, true); // - Setup the mock HTTP Request var request = new Mock<System.Web.HttpRequestBase>(); var context = new Mock<System.Web.HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); System.Collections.Specialized.NameValueCollection formParameters = new System.Collections.Specialized.NameValueCollection(); // NOTE: adding items to the formParameter collection is possible here request.SetupGet(x => x.Form).Returns(formParameters); // - Create the fake instance repo and the job execution controller QuartzAdmin.web.Models.IInstanceRepository instanceRepo = new Fakes.FakeInstanceRepository(); instanceRepo.Save(GetTestInstance()); QuartzAdmin.web.Controllers.JobExecutionController jec = new QuartzAdmin.web.Controllers.JobExecutionController(instanceRepo); // - Set the fake request for the controller jec.ControllerContext = new System.Web.Mvc.ControllerContext(context.Object, new System.Web.Routing.RouteData(), jec); // Act System.Web.Mvc.ActionResult result = jec.RunNow("MyTestInstance", "TestGroup", "TestJob"); //Assert Assert.IsTrue(result is System.Web.Mvc.ContentResult && ((System.Web.Mvc.ContentResult)result).Content == "Job execution started"); }
protected void Application_Start() { ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); // Depends on MVC2Futures library to make MVC ver2 controllers to accept JSON serialized objects log4net.Config.XmlConfigurator.Configure(); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); //TODO Protect Quartz from getting recycled. #9 ISchedulerFactory schedFact = new StdSchedulerFactory(); // get a scheduler IScheduler sched = schedFact.GetScheduler(); // construct job info JobDetail jobDetail = new JobDetail("mySendMailJob", typeof(EmailJob)); // fire every minute to check for queued e-mail messages in the db Trigger trigger = TriggerUtils.MakeMinutelyTrigger(1); trigger.Name = "mySendMailTrigger"; // schedule the job for execution sched.ScheduleJob(jobDetail, trigger); sched.Start(); log4net.ILog log = log4net.LogManager.GetLogger(typeof(MvcApplication)); log.Info("Quartz Queue started! Application Started!"); //To flush logger buffer immediatley if not configured in the config file //foreach (IAppender appender in log.Logger.Repository.GetAppenders()) //{ // var buffered = appender as BufferingAppenderSkeleton; // if (buffered != null) // { // buffered.Flush(); // } //} }
private static void Register(IScheduler scheduler) { var jobDetail = new JobDetail("GamificationCheckStatusJob", null, typeof(TrackerController)); Trigger trigger = TriggerUtils.MakeMinutelyTrigger(30); trigger.Name = "GamificationCheckStatus"; scheduler.ScheduleJob(jobDetail, trigger); }
public void LoadDataJob(string model, string path, dynamic user) { string typeName = "MVC_Husk.Infrastructure.BackgroundJobs.Load" + model + "Job"; Type modelType = Type.GetType(typeName); if (modelType != null) { string description = "Load File for " + model + " at " + path; JobDetail details = new JobDetail(description, modelType); details.JobDataMap["path"] = path; details.Description = "Job that loads Seasonal Products data uploaded via the application into the database"; details.Group = "Data Load"; Trigger trigger = new SimpleTrigger("QuartzManager LoadDataJob", DateTime.Now); trigger.Description = "Trigger immediately"; trigger.Group = "Immediate"; dynamic result = _jobs.CreateJob(description, 1, DateTime.Now, user.ID); details.JobDataMap["QueueID"] = result.JobId; _scheduler.ScheduleJob(details, trigger); } else { _logger.LogError("There is no " + typeName + "defined"); throw new NullReferenceException("There is no " + typeName + "defined"); } }
public void Run() { ILog log = LogManager.GetLogger(typeof(SimpleExample)); log.Info("------- Initializing ----------------------"); ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- Scheduling Jobs -------------------"); DateTime runTime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow); JobDetail job = new JobDetail("job1", "group1", typeof(HelloJob)); SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime); sched.ScheduleJob(job, trigger); sched.Start(); log.Info("------- Started Scheduler -----------------"); // wait long enough so that the scheduler as an opportunity to // run the job! log.Info("------- Waiting 90 seconds... -------------"); // wait 90 seconds to show jobs Thread.Sleep(90 * 1000); // shut down the scheduler log.Info("------- Shutting Down ---------------------"); sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); }
static void Main(string[] args) { ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); IScheduler sched1 = sf.GetScheduler(); JobDetail job = new JobDetail("job1","group1",typeof(SimpleJob)); //DateTime runtime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);//下一分钟 //DateTime runtime = TriggerUtils.GetNextGivenSecondDate(null, 15);//15秒后 //每一秒运行一次 重复十次 开始时间为now 结束时间为null //SimpleTrigger trigger = new SimpleTrigger("trigger1", "gropp1", "job1", "group1", DateTime.UtcNow, null, 10, TimeSpan.FromSeconds(10)); SimpleTrigger trigger = new SimpleTrigger("trigger1", "gropp1", DateTime.UtcNow, null, SimpleTrigger.RepeatIndefinitely, TimeSpan.FromSeconds(1)); sched.ScheduleJob(job,trigger); LogManager.GetLogger(typeof(Program)).Info("开始循环,每10秒运行一次,重复10次"); sched.Start(); //Thread.Sleep(90 * 1000); }
/// <summary> /// 执行任务 /// </summary> /// <param name="scheduler"></param> /// <remarks> /// </remarks> public static void ExecuteJobs(IScheduler scheduler) { SystemTaskSectionConfig sectionConfig = Config.GetSection<SystemTaskSectionConfig>("systemTaskSection"); foreach (SystemTaskOfDailyExcutorEntity item in sectionConfig.SystemTaskOfDailyExcutorList) { if (item.IsUse == false) { continue; } JobDetail jobDetail = new JobDetail(item.Name + "Job", null, item.Type); Trigger triger = TriggerUtils.MakeDailyTrigger(item.ExcuteHour, item.ExcuteMinute); triger.Name = item.Name + "Triger"; //0.由于采用了2种方式执行job,为了防止对同一个job可能多次的执行,就需要在job内部自己控制重复的逻辑。 //1.如果系统一直未退出应用程序域,那么就可以使用Schedule来执行 if (scheduler != null) { scheduler.ScheduleJob(jobDetail, triger); } //2.如果系统在退出应用程序域的时间段内已经过了task执行的时间,那么手动执行task CommonHandle<SystemTaskOfDailyExcutorEntity> commonHandle = new CommonHandle<SystemTaskOfDailyExcutorEntity>(ExcuteJobManaul); commonHandle.BeginInvoke(item, null, null); } }
public Form1() { InitializeComponent(); // Instantiate the Quartz.NET scheduler StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(); IScheduler scheduler = schedulerFactory.GetScheduler(); // Instantiate the JobDetail object passing in the type of your // custom job class. Your class merely needs to implement a simple // interface with a single method called "Execute". JobDetail job = new JobDetail( "job1", "group1", typeof( MyJobClass ) ); DateTime now = DateTime.Now.AddMinutes( 1 ); DateTime dt = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0 ); CronTrigger trigger = new CronTrigger( "trigger 1", "group1", "job1", "group1", "5 * * * * ?" ); //CronTrigger ct = new CronTrigger( "trigger 1", "group1", "job1", "group1", "5 * * * * ?" ); //SimpleTrigger trigger = new SimpleTrigger( "trigger 1", new DateTime( dt.ToFileTimeUtc() ), null, SimpleTrigger.RepeatIndefinitely, new TimeSpan( 0, 0, 0, 15 ) ); //trigger.JobName = "job1"; //trigger.Group = "group1"; //trigger.JobGroup = "group1"; // Instantiate a trigger using the basic cron syntax. // This tells it to run at 1AM every Monday - Friday. // Add the job to the scheduler scheduler.AddJob( job, true ); scheduler.ScheduleJob( trigger ); scheduler.Start(); }
static void Main() { try { if (log.IsDebugEnabled) log.Debug("Apache log4net successfully initialized."); var jobDetail = new JobDetail("SampleJob", "SampleJobGroup", typeof(CronJob)); var cronTrigger = new CronTrigger("SampleTrigger", "SampleTriggerGroup", "0/4 * * * * ? *"); var schedulerFactory = new StdSchedulerFactory(); var scheduler = schedulerFactory.GetScheduler(); scheduler.ScheduleJob(jobDetail, cronTrigger); scheduler.Start(); var msg = String.Format("Starting Quartz.NET cron job ({0})", cronTrigger.CronExpressionString); if (!log.IsInfoEnabled) Console.WriteLine(msg); log.Info(msg); } catch (SchedulerException err) { var msg = String.Format("Quartz.NET Scheduler error: {0}", err.Message); if (!log.IsErrorEnabled) Console.WriteLine(msg); log.Error(msg); Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(true); } }
/// <summary> /// Don't use this method. It is used by QueuedJob's Execute(). /// </summary> public void ScheduleNext() { lock (queueLock) { if (queue.Count > 0) { QueuedJobDetail queuedJobDetail = queue.Dequeue(); JobDetail jobDetail = new JobDetail("QueueJob" + counter, null, queuedJobDetail.JobType); jobDetail.Volatile = true; jobDetail.JobDataMap = queuedJobDetail.JobDataMap; jobDetail.JobDataMap["JobQueue"] = this; Trigger trigger = new SimpleTrigger("QueueJobTrigger" + counter, null, queuedJobDetail.StartTime); scheduler.ScheduleJob(jobDetail, trigger); counter++; scheduled = true; return; } scheduled = false; } }
protected override void OnStart(string[] args) { logger.Log(LogLevel.Info, String.Format("Starting Open Payments Processor")); // construct a scheduler factory ISchedulerFactory schedFact = new StdSchedulerFactory(); IScheduler sched = schedFact.GetScheduler(); Context ctx = new Context(); JobDetail jobDetail = new JobDetail("myJob", null, typeof(ProcessOpenPaymentJob)); Trigger trigger = TriggerUtils.MakeDailyTrigger(5, 00); trigger.StartTimeUtc = DateTime.UtcNow; trigger.Name = "myTrigger1"; sched.ScheduleJob(jobDetail, trigger); try { logger.Log(LogLevel.Info, String.Format("Starting Scheduler")); sched.Start(); } catch (Exception ex) { logger.Log(LogLevel.Info, String.Format("Exception Starting Scheduler {0}", ex.Message)); throw; } }
private void InitializeScheduler() { try { if (scheduler != null) { return; } Logger.Log.Debug("Initializing Collector scheduler..."); schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); // BatDongSanJob jobDetail = new JobDetail("BatDongSanJob", null, typeof(BatDongSanJob)); string cronEx = CollectorConfiguration.BatDongSan.BatDongSanCronTriggerExpression; cronTrigger = new CronTrigger( "BatDongSanTrigger", null, cronEx ); cronTrigger.StartTimeUtc = DateTime.UtcNow; scheduler.ScheduleJob(jobDetail, cronTrigger); Logger.Log.Debug("Initialize Collector scheduler completely."); } catch (Exception ex) { Logger.Log.Error(ex); } }
static void Main(string[] args) { ISchedulerFactory schedFact = new StdSchedulerFactory(); sched = schedFact.GetScheduler(); JobDetail jobDetail = new JobDetail("OrdersJob", null, typeof(OrdersJob)); Trigger trigger = TriggerUtils.MakeMinutelyTrigger("GodServiceOrdersJob"); sched.ScheduleJob(jobDetail, trigger); sched.Start(); }
protected override void OnStart(string[] args) { try { //0 0 12 * * ? 每天12点触发 //0 15 10 ? * * 每天10点15分触发 //0 15 10 * * ? 每天10点15分触发 //0 15 10 * * ? * 每天10点15分触发 //0 15 10 * * ? 2005 2005年每天10点15分触发 //0 * 14 * * ? 每天下午的 2点到2点59分每分触发 //0 0/5 14 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) //0 0/5 14,18 * * ? 每天下午的 2点到2点59分(整点开始,每隔5分触发) //每天下午的 18点到18点59分(整点开始,每隔5分触发) //0 0-5 14 * * ? 每天下午的 2点到2点05分每分触发 //0 10,44 14 ? 3 WED 3月分每周三下午的 2点10分和2点44分触发 //0 15 10 ? * MON-FRI 从周一到周五每天上午的10点15分触发 //0 15 10 15 * ? 每月15号上午10点15分触发 //0 15 10 L * ? 每月最后一天的10点15分触发 //0 15 10 ? * 6L 每月最后一周的星期五的10点15分触发 //0 15 10 ? * 6L 2002-2005 从2002年到2005年每月最后一周的星期五的10点15分触发 //0 15 10 ? * 6#3 每月的第三周的星期五开始触发 //0 0 12 1/5 * ? 每月的第一个中午开始每隔5天触发一次 //0 11 11 11 11 ? 每年的11月11号 11点11分触发(光棍节) //发邮件工作任务 JobDetail m_TimingMailJobDetail1 = new JobDetail("打印测试文件", Guid.NewGuid().ToString("N"), typeof(RegularMailJob.RegularMail_T2)); JobDetail m_TimingMailJobDetail2 = new JobDetail("打印测试文件", Guid.NewGuid().ToString("N"), typeof(RegularMailJob.RegularMail_T2)); JobDetail m_TimingMailJobDetail3 = new JobDetail("打印测试文件", Guid.NewGuid().ToString("N"), typeof(RegularMailJob.RegularMail_T2)); //Trigger m_TimingMailTrigger = new SimpleTrigger(Guid.NewGuid().ToString("N"), Guid.NewGuid().ToString("N"), m_TimingMailJobDetail.Name, m_TimingMailJobDetail.Group, DateTime.UtcNow, null, 0, TimeSpan.FromDays(7)); //CronTrigger trigger = new CronTrigger("打印", "group1", "0/30 * * * * ?"); //从周一到周五每天上午的10点15分触发 CronTrigger trigger1 = new CronTrigger("打印1", "group1", "0 20 15 ? * MON-FRI"); CronTrigger trigger2 = new CronTrigger("打印2", "group2", "0 25 15 ? * MON-FRI"); CronTrigger trigger3 = new CronTrigger("打印3", "group3", "0 15 15 ? * MON-FRI"); SchedulerManager.GetScheduler().ScheduleJob(m_TimingMailJobDetail1, trigger1); log.Info("任务:" + m_TimingMailJobDetail1.FullName + " 已经调度成功!"); SchedulerManager.GetScheduler().ScheduleJob(m_TimingMailJobDetail2, trigger2); log.Info("任务:" + m_TimingMailJobDetail2.FullName + " 已经调度成功!"); SchedulerManager.GetScheduler().ScheduleJob(m_TimingMailJobDetail3, trigger3); log.Info("任务:" + m_TimingMailJobDetail3.FullName + " 已经调度成功!"); SchedulerManager.GetScheduler().Start(); log.Info("service started ok"); } catch (Exception ex) { log.Error("service started fail", ex); this.Stop(); } }
public static void ScheduleHeartbeatJob(string projectId) { string jobName = "Heartbeat_" + projectId; JobDetail job = new JobDetail(jobName, jobName, typeof(HeartbeatJob)); job.JobDataMap["projectId"] = projectId; CronTrigger trigger = new CronTrigger(jobName, jobName, jobName, jobName, FIVE_MINUTE_PATTERN); engine.AddJob(job, true); DateTime ft = engine.ScheduleJob(trigger); }
public override void TestAfterPropertiesSet_JobDetailGiven() { const string jobName = "jobName"; const string jobGroup = "jobGroup"; JobDetail jd = new JobDetail(jobName, jobGroup, typeof (NoOpJob)); cronTrigger.JobDetail = jd; cronTrigger.AfterPropertiesSet(); base.TestAfterPropertiesSet_JobDetailGiven(); Assert.AreSame(jd, cronTrigger.JobDetail, "job details weren't same"); }
public override void AddJob(Job job) { JobNames.Add(job.Name); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(Common.Properties.QuartzSchedulerProperties); IScheduler scheduler = schedulerFactory.GetScheduler(); JobDetail jobDetail = new JobDetail(job.Name, "sequential", job.GetType(), false, true, true); jobDetail.JobDataMap = job.JobDataMap; scheduler.AddJob(jobDetail, true); }
public override void Execute(Job job) { Instances.MainCounterStore.Increment(new Caching.CacheKey(Caching.CacheKeyPrefix.JobQueued, Timeslots.GetCurrentTimeslot().StartTime.ToString()), () => 0); JobDetail jobDetail = new JobDetail(job.Name, "immediate", job.GetType()); jobDetail.JobDataMap = job.JobDataMap; SimpleTrigger trigger = new SimpleTrigger("Trigger" + job.Name, "immediate"); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(Common.Properties.QuartzSchedulerProperties); IScheduler scheduler = schedulerFactory.GetScheduler(); scheduler.ScheduleJob(jobDetail, trigger); }
public static void ScheduleSqlJob(string projectId) { string jobName = "Report_" + projectId; JobDetail job = new JobDetail(jobName, jobName, typeof(SqlJob)); job.JobDataMap["projectId"] = projectId; job.JobDataMap["lastTime"] = Monitor.Common.ScheduleSetting.GetLastTime(projectId); CronTrigger trigger = new CronTrigger(jobName, jobName, jobName, jobName, Monitor.Common.SystemInternalSetting.Frequence); engine.AddJob(job, true); DateTime ft = engine.ScheduleJob(trigger); }
static void Main(string[] args) { Console.WriteLine("Starting scheduler..."); var properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "RemoteServerTestScheduler"; // set thread pool infoD:\Projects\QuartzMaster\QuartzMaster.TestServerHost\Program.cs properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; // set remoting expoter properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz"; properties["quartz.scheduler.exporter.port"] = "500"; properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler"; properties["quartz.scheduler.exporter.channelType"] = "tcp"; var schedulerFactory = new StdSchedulerFactory(properties); scheduler = schedulerFactory.GetScheduler(); // define the job and ask it to run var map = new JobDataMap(); map.Put("msg", "Some message!"); map.Put("msg 2", "Some message 2!"); map.Put("msg 3", "Some message 3!"); var job = new JobDetail("localJob", "default", typeof(NoOpJob)) { JobDataMap = map }; var job2 = new JobDetail("localJob 2", "default", typeof(NoOpJob)) { JobDataMap = map }; var trigger2 = new SimpleTrigger("Simple Trigger", "default", "localJob 2", "default", DateTime.Now, DateTime.Now.AddMinutes(10), SimpleTrigger.RepeatIndefinitely, new TimeSpan(0, 0, 45)); var trigger = new CronTrigger("remotelyAddedTrigger", "default", "localJob", "default", DateTime.UtcNow, null, "/5 * * ? * *"); var trigger3 = new SimpleTrigger("remotelyAddedTriggerB", "default", "localJob", "default", DateTime.Now, DateTime.Now.AddMinutes(10), SimpleTrigger.RepeatIndefinitely, new TimeSpan(0, 0, 45)); // schedule the job scheduler.ScheduleJob(job, trigger3); scheduler.ScheduleJob(job2, trigger2); scheduler.Start(); Console.WriteLine("Scheduler has been started."); Console.WriteLine("Press any key to stop scheduler"); Console.ReadKey(); scheduler.Shutdown(); }
public static void FireOffSchedules() { var sched = GetScheduler(); var jobDetail = new JobDetail("myJob", null, typeof(StatusTrackerJob)); var trigger = TriggerUtils.MakeSecondlyTrigger(5); trigger.StartTimeUtc = DateTime.UtcNow; trigger.Name = "myTrigger"; sched.ScheduleJob(jobDetail, trigger); }
public static void Schedule() { ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler schedule = factory.GetScheduler(); schedule.Start(); JobDetail job = new JobDetail("SynochronishOU", typeof(SynchronishJob)); Trigger trigger = TriggerUtils.MakeHourlyTrigger(2); trigger.StartTimeUtc = DateTime.UtcNow; trigger.Name = "Syn"; schedule.ScheduleJob(job, trigger); }
public void Schedule(DateTime date, Action action) { JobDetail jobDetail = new JobDetail(Guid.NewGuid().ToString(), null, typeof(DateJob)); jobDetail.JobDataMap["Listener"] = action; SimpleTrigger trigger = new SimpleTrigger(Guid.NewGuid().ToString(), null, date, null, 0, TimeSpan.Zero); sched.ScheduleJob(jobDetail, trigger); }
protected void Application_Start(object sender, EventArgs e) { var context = ContextRegistry.GetContext(); var scheduler = (IScheduler) context.GetObject("scheduler"); scheduler.Start(); var jobDetail = new JobDetail("myJob", null, typeof(NoOpJob)); var trigger = TriggerUtils.MakeHourlyTrigger(); trigger.StartTimeUtc = DateTime.UtcNow; trigger.Name = "myTrigger"; scheduler.ScheduleJob(jobDetail, trigger); }
public void TestForQuartzTrigger() { IScheduler scheduler = binder.GetInstance<IScheduler>(); JobDetail jobDetail = new JobDetail("TestQuartz", typeof(TestJob)); DateTime dateTime = DateTime.UtcNow.AddSeconds(1); Trigger trigger = new SimpleTrigger("TestQuartzTrigger", dateTime); scheduler.ScheduleJob(jobDetail, trigger); Thread.Sleep(3000); Assert.IsTrue(Triggered); }
public void Schedule(IScheduler scheduler) { var jobDetail = new JobDetail(Name, null, SchedulerHelper.GetJobType(ReminderService.JobToRun)); jobDetail.JobDataMap["ReminderService"] = ReminderService; jobDetail.JobDataMap["Account"] = Account; jobDetail.JobDataMap["Location"] = ReminderService.Location; var trigger = new ZmanimTrigger(Name, ReminderService.Location, z => ( (DateTime)SchedulerHelper.GetMethodInfo(ReminderService.ZmanName).Invoke(z, null)) .AddSeconds(ReminderService.AddSeconds)); scheduler.ScheduleJob(jobDetail, trigger); }
public void LongRunningJob(dynamic user) { string description = "Long Running Task"; JobDetail details = new JobDetail(description, typeof(LongRunningNotepadJob)); details.Description = "Long running job"; details.Group = "External executable job"; Trigger trigger = new SimpleTrigger("QuartzManager Long Running Task", DateTime.Now); trigger.Description = "Trigger immediately"; trigger.Group = "Immediate"; dynamic result = _jobs.CreateJob(description, 1, DateTime.Now, user.ID, "LongRunning", 1); details.JobDataMap["QueueID"] = result.JobId; _scheduler.ScheduleJob(details, trigger); }
public static void Start() { //每隔一段时间执行任务 IScheduler sched; ISchedulerFactory sf = new StdSchedulerFactory(); sched = sf.GetScheduler(); JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob为实现了IJob接口的类 DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);//5秒后开始第一次运行 TimeSpan interval = TimeSpan.FromHours(1);//每隔10秒执行一次 Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null, SimpleTrigger.RepeatIndefinitely, interval);//每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定 sched.AddJob(job, true); sched.ScheduleJob(trigger); sched.Start(); //要关闭任务定时则需要sched.Shutdown(true) }
/// <summary> /// 将任务移入任务池 /// </summary> /// <param name="taskid"></param> /// <param name="taskruntimeinfo"></param> /// <returns></returns> public bool Add(string taskid, NodeTaskRuntimeInfo taskruntimeinfo) { lock (_locktag) { if (!TaskRuntimePool.ContainsKey(taskid)) { JobDetail jobDetail = new JobDetail(taskruntimeinfo.TaskModel.id.ToString(), taskruntimeinfo.TaskModel.categoryid.ToString(), typeof(TaskJob));// 任务名,任务组,任务执行类 var trigger = CornFactory.CreateTigger(taskruntimeinfo); _sched.ScheduleJob(jobDetail, trigger); TaskRuntimePool.Add(taskid, taskruntimeinfo); return true; } return false; } }
/// <summary> /// Create a JobExcecutionContext with the given context data. /// </summary> public JobExecutionContext(IScheduler scheduler, TriggerFiredBundle firedBundle, IJob job) { this.scheduler = scheduler; trigger = firedBundle.Trigger; calendar = firedBundle.Calendar; jobDetail = firedBundle.JobDetail; this.job = job; recovering = firedBundle.Recovering; fireTimeUtc = firedBundle.FireTimeUtc; scheduledFireTimeUtc = firedBundle.ScheduledFireTimeUtc; prevFireTimeUtc = firedBundle.PrevFireTimeUtc; nextFireTimeUtc = firedBundle.NextFireTimeUtc; jobDataMap = new JobDataMap(); jobDataMap.PutAll(jobDetail.JobDataMap); jobDataMap.PutAll(trigger.JobDataMap); }
/// <summary> /// Checks equality between given job detail and this instance. /// </summary> /// <param name="detail">The detail to compare this instance with.</param> /// <returns></returns> public bool Equals(JobDetail detail) { return(IsEqual(detail)); }
/// <summary> <p> /// Create a <see cref="ObjectAlreadyExistsException" /> and auto-generate a /// message using the name/group from the given <see cref="JobDetail" />. /// </p> /// /// <p> /// The message will read: <br />"Unable to store Job with name: '__' and /// group: '__', because one already exists with this identification." /// </p> /// </summary> public ObjectAlreadyExistsException(JobDetail offendingJob) : base( string.Format(CultureInfo.InvariantCulture, "Unable to store Job with name: '{0}' and group: '{1}', because one already exists with this identification.", offendingJob.Name, offendingJob.Group)) { }
protected virtual bool IsEqual(JobDetail detail);
public bool Equals(JobDetail detail);
protected void Application_Start(object sender, EventArgs e) { ISchedulerFactory sf = new StdSchedulerFactory(); DateTime runTime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow); JobDetail job = new JobDetail("job1", "group1", typeof(HelloJob)); sched = sf.GetScheduler(); SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime); sched.ScheduleJob(job, trigger); sched.Start(); }