Exemple #1
0
        public async Task Start()
        {
            var factory   = new StdSchedulerFactory();
            var scheduler = await factory.GetScheduler();

            await scheduler.Start();

            //Jobs
            var storeDailyGamesJob = JobBuilder.Create <StoreDailyGamesJob>()
                                     .WithIdentity("storeDailyGamesJob")
                                     .Build();

            //Triggers
            var storeDailyGamesTrigger = TriggerBuilder.Create()
                                         .WithDailyTimeIntervalSchedule(s => s.WithIntervalInHours(24)
                                                                        .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(15, 46))
                                                                        .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")))
                                         .Build();

            //Pass params to jobs through jobdatamap
            storeDailyGamesJob.JobDataMap["gameRepo"]        = _gameRepository;
            storeDailyGamesJob.JobDataMap["messageBusSetup"] = _messageBusSetup;
            storeDailyGamesJob.JobDataMap["logger"]          = _logger;

            var dailyStoreJobListener = new DailyStoreJobListener {
                Name = "dailyStoreJobListener"
            };

            scheduler.ListenerManager.AddJobListener(dailyStoreJobListener, KeyMatcher <JobKey> .KeyEquals(new JobKey("storeDailyGamesJob")));

            await scheduler.ScheduleJob(storeDailyGamesJob, storeDailyGamesTrigger);
        }
Exemple #2
0
        public void TriggerListenerNotFired()
        {
            // Add Quartz (with 1 triggerlistener)
            Container.AddFacility <QuartzFacility>(f =>
            {
                f.TriggerListeners = new[]
                {
                    new TriggerListener(Container.Resolve <ITriggerListener>(),
                                        new IMatcher <TriggerKey>[]
                    {
                        KeyMatcher <TriggerKey> .KeyEquals(new TriggerKey("FakeTrigger", "FakeGroup"))
                    })
                };
                f.Properties = QuartzProperties;
            });


            // Schedule Job
            ScheduleJob();
            Sleep(2);

            // Assert
            TestTriggerListener.Verify(m => m.TriggerComplete(It.IsAny <ITrigger>(), It.IsAny <IJobExecutionContext>(),
                                                              It.IsAny <SchedulerInstruction>(), It.IsAny <CancellationToken>()), Times.Never);
        }
        private static void Test002(IScheduler Scheduler)
        {
            IJobDetail job = JobBuilder.Create <SimpleJob>()
                             .WithIdentity("job1", "myJobGroup")
                             .Build();

            ITrigger trigger = TriggerBuilder
                               .Create()
                               .WithSchedule(DailyTimeIntervalScheduleBuilder
                                             .Create()
                                             .OnMondayThroughFriday()
                                             .WithIntervalInSeconds(10))
                               .StartNow()
                               .WithIdentity("trigger1", "myJobGroup")
                               .Build();

            Scheduler.ScheduleJob(job, trigger);

            var myJobListener = new MyJobListener();

            myJobListener.Name         = "MyJobListener";
            myJobListener.JobExecuted += OnJobExecuted;

            Scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher <JobKey> .KeyEquals(new JobKey("job1", "myJobGroup")));

            GetAllJobs(Scheduler);
        }
Exemple #4
0
        public void ScheduleTask(ScheduledTask task)
        {
            if (task.ScheduledTaskId == default(long))
            {
                throw new ArgumentException("Scheduling a task requires the task to be saved to the database and have a ScheduledTaskId assigned.");
            }

            JobKey     jobKey = JobKey.Create(task.TaskName, JobKey.DefaultGroup);
            IJobDetail job;

            if (!m_QuartzScheduler.CheckExists(jobKey))
            {
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.Add("connectionString", m_Controller.ConnectionString);
                jobDataMap.Add("threadSynchronizer", m_ThreadSynchronizer);
                jobDataMap.Add("scheduledTaskId", task.ScheduledTaskId);

                job = JobBuilder.Create <ExecuteSequenceJob>()
                      .WithIdentity(jobKey)
                      .SetJobData(jobDataMap)
                      .StoreDurably()
                      .Build();
                m_QuartzScheduler.AddJob(job, false);

                ExecuteSequenceJobListener jobListener = new ExecuteSequenceJobListener(task.TaskName);
                jobListener.TaskStart    += jobListener_TaskStart;
                jobListener.TaskComplete += jobListener_TaskComplete;
                m_QuartzScheduler.ListenerManager.AddJobListener(jobListener, KeyMatcher <JobKey> .KeyEquals(jobKey));
            }
            else
            {
                job = m_QuartzScheduler.GetJobDetail(jobKey);
                m_QuartzScheduler.UnscheduleJobs(m_QuartzScheduler.GetTriggersOfJob(jobKey)
                                                 .Select(t => t.Key)
                                                 .ToList());
            }

            if (task.Enabled)
            {
                task.NextScheduledRunTimeUtc = DateTime.MaxValue;
                foreach (TriggerBuilder triggerBuilder in TriggerBuilderFactory.CreateForSchedule(task.TaskName, task.RunSchedule))
                {
                    ITrigger trigger = triggerBuilder
                                       .ForJob(job)
                                       .Build();
                    DateTimeOffset nextScheduledRunTimeUtc = m_QuartzScheduler.ScheduleJob(trigger);
                    if (nextScheduledRunTimeUtc.DateTime < task.NextScheduledRunTimeUtc.Value)
                    {
                        task.NextScheduledRunTimeUtc = nextScheduledRunTimeUtc.DateTime;
                    }
                }
            }
            else
            {
                task.NextScheduledRunTimeUtc = null;
            }

            m_Controller.SetScheduledTaskNextScheduledRunTime(task.ScheduledTaskId, task.NextScheduledRunTimeUtc);
        }
Exemple #5
0
        private void RegListener <From, To>()
        {
            IJobListener      listener5 = new JOBListener <From, To>();
            JobKey            key5      = new JobKey(typeof(From).Name);
            IMatcher <JobKey> matcher5  = KeyMatcher <JobKey> .KeyEquals(key5);

            scheduler.ListenerManager.AddJobListener(listener5, matcher5);
        }
Exemple #6
0
        /// <summary>
        /// 添加Job监听
        /// </summary>
        /// <param name="detail"></param>
        private void AddListener(IJobDetail detail)
        {
            var jobListener = new JobListener {
                Name = detail + "_listener"
            };
            IMatcher <JobKey> matcher = KeyMatcher <JobKey> .KeyEquals(detail.Key);

            _scheduler.ListenerManager.AddJobListener(jobListener, matcher);
        }
Exemple #7
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(TriggeringAJobUsingJobListenersExample));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");

            log.Info("------- Scheduling Jobs -------------------");

            // schedule a job to run immediately
            IJobDetail job = JobBuilder.Create <SimpleJob1>()
                             .WithIdentity("job1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1")
                               .StartNow()
                               .Build();

            // Set up the listener
            IJobListener      listener = new SimpleJob1Listener();
            IMatcher <JobKey> matcher  = KeyMatcher <JobKey> .KeyEquals(job.Key);

            sched.ListenerManager.AddJobListener(listener, matcher);

            // schedule the job to run
            await sched.ScheduleJob(job, trigger);

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            await sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");

            // wait 30 seconds to show jobs
            await Task.Delay(TimeSpan.FromSeconds(30));

            // executing...

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }
        private IApinationListener StartApinationPolling()
        {
            scheduler.ListenerManager.AddJobListener(apinationJobListener, KeyMatcher <JobKey> .KeyEquals(job.Key));
            scheduler.ScheduleJob(job, trigger);

            scheduler.TriggerJob(job.Key);

            return(apinationJobListener);
        }
Exemple #9
0
        private async Task Start(JobTaskView view, TaskLoadContext lc)
        {
            //throw

            //在应用程序域中创建实例返回并保存在job中,这是最终调用任务执行的实例
            TaskBase instance = AssemblyHelper.CreateTaskInstance(lc, view.JobTask.Id, view.JobTask.AssemblyName, view.JobTask.ClassName);

            if (instance == null)
            {
                throw new InvalidCastException($"任务实例创建失败,请确认目标任务是否派生自TaskBase类型。程序集:{view.JobTask.AssemblyName},类型:{view.JobTask.ClassName}");
            }
            // instance.logger = new LogWriter(); ;
            JobDataMap map = new JobDataMap
            {
                new KeyValuePair <string, object> ("domain", lc),
                new KeyValuePair <string, object> ("instance", instance),
                new KeyValuePair <string, object> ("name", view.JobTask.Title),
                new KeyValuePair <string, object> ("params", ConvertParamsJson(view.JobTask.CustomParamsJson)),
                new KeyValuePair <string, object> ("keepers", view.Keepers),
                new KeyValuePair <string, object> ("children", view.Children)
            };

            try
            {
                IJobDetail job = JobBuilder.Create <RootJob>()
                                 .WithIdentity(view.JobTask.Id.ToString())
                                 .UsingJobData(map)
                                 .Build();

                //添加触发器
                var listener = new JobRunListener(view.JobTask.Id.ToString());
                listener.OnSuccess += StartedEventAsync;
                _scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(new JobKey(view.JobTask.Id.ToString())));

                if (!CronExpression.IsValidExpression(view.JobTask.CronExpression))
                {
                    throw new Exception("cron表达式验证失败");
                }
                CronTriggerImpl trigger = new CronTriggerImpl
                {
                    CronExpressionString = view.JobTask.CronExpression,
                    Name        = view.JobTask.Title,
                    Key         = new TriggerKey(view.JobTask.Id.ToString()),
                    Description = view.JobTask.Remark
                };

                await _scheduler.ScheduleJob(job, trigger);
            }
            catch (Exception ex)
            {
                throw new SchedulerException(ex);
            }
            _logger.LogInformation($"任务[{view.JobTask.Title}]启动成功!", view.JobTask.Id);
        }
Exemple #10
0
        private static async Task Start(IHosSchedule schedule)
        {
            JobDataMap map = new JobDataMap
            {
                new KeyValuePair <string, object> ("instance", schedule),
            };
            string jobKey = schedule.Main.Id.ToString();

            try
            {
                IJobDetail job = JobBuilder.Create().OfType(schedule.GetQuartzJobType()).WithIdentity(jobKey).UsingJobData(map).Build();

                //添加监听器
                var listener = new JobRunListener(jobKey);
                listener.OnSuccess += StartedEvent;
                _scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(new JobKey(jobKey)));

                await _scheduler.ScheduleJob(job, GetTrigger(schedule.Main), schedule.CancellationTokenSource.Token);
            }
            catch (Exception ex)
            {
                throw new SchedulerException(ex);
            }
            LogHelper.Info($"任务[{schedule.Main.Title}]启动成功!", schedule.Main.Id);

            _ = Task.Run(() =>
            {
                while (true)
                {
                    if (schedule.RunnableInstance == null)
                    {
                        break;
                    }
                    var log = schedule.RunnableInstance.ReadLog();
                    if (log != null)
                    {
                        LogManager.Queue.Write(new SystemLogEntity
                        {
                            Category   = log.Category,
                            Message    = log.Message,
                            ScheduleId = log.ScheduleId,
                            Node       = log.Node,
                            StackTrace = log.StackTrace,
                            TraceId    = log.TraceId,
                            CreateTime = log.CreateTime
                        });
                    }
                    else
                    {
                        Thread.Sleep(3000);
                    }
                }
            });
        }
        // Adding a JobListener that is interested in a particular job:
        public static async Task AddAJobListener()
        {
            NameValueCollection props = new NameValueCollection
            {
                { "quartz.serializer.type", "binary" }
            };
            StdSchedulerFactory factory   = new StdSchedulerFactory(props);
            IScheduler          scheduler = await factory.GetScheduler();

            IJobListener myJobListener = new GggJobListener();

            scheduler.ListenerManager.AddJobListener(myJobListener, KeyMatcher <JobKey> .KeyEquals(new JobKey("myJobName", "myJobGroup")));
        }
        public static async Task Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration().WriteTo.ColoredConsole().CreateLogger();

            var host = new HostBuilder()
                       .ConfigureAppConfiguration(x => x.AddJsonFile("appsettings.json"))
                       .ConfigureServices((services) =>
            {
                services.AddJobService <ConsolePrintJob>((job, trigger) =>
                {
                    job.WithIdentity("ConsolePrintJob").WithDescription("Simple job");
                    trigger.StartNow().WithSimpleSchedule((x) => x.WithIntervalInSeconds(5).RepeatForever());
                });
                services.AddJobService <LogWriteJob>((job, trigger) =>
                {
                    job.WithIdentity("LogWriteJob").WithDescription("Simple job");
                    trigger.StartNow().WithSimpleSchedule((x) => x.WithIntervalInSeconds(2).RepeatForever());
                });
                services.AddJobService <Job1>((job) =>
                {
                    job.WithIdentity("Job1");
                });
            })
                       // You can use the other `UserQuartz` 2 methods
                       // if you only want to configure either the scheduler factory
                       // or the scheduler instance
                       .UseQuartz(
                (context, config) =>
            {
                // Here you can further customize options passed down to the StdSchedulerFactory
                config.Set("quartz.threadPool.threadCount", Environment.ProcessorCount.ToString());
            },
                (context, provider, scheduler) =>
            {
                // You can further configure the scheduler instance here, like
                // add job listeners, trigger listeners, etc.
                // DO NOT call the Start method here as it will be automatically
                // invoked by the hosted service once it is started.
                var listener = new JobChainingJobListener("Chain");
                var firstJob = new JobKey("ConsolePrintJob");
                listener.AddJobChainLink(firstJob, new JobKey("Job1"));
                scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(firstJob));
            }
                )
                       .UseConsoleLifetime()
                       .UseSerilog()
                       .Build();

            await host.RunAsync();
        }
        public async Task RunAsync()
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            IJobDetail job = JobBuilder.Create <SimpleJob1>()
                             .WithIdentity("job1", "jobGroup1")
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "triggerGroup1")
                                     .StartNow()
                                     .WithSimpleSchedule(x => x.WithIntervalInSeconds(20).RepeatForever())
                                     .Build();

            scheduler.ListenerManager.AddJobListener(new JobListener(), KeyMatcher <JobKey> .KeyEquals(job.Key));

            DateTimeOffset df = await scheduler.ScheduleJob(job, trigger);

            ConsoleExtend.WriteLineRed($"作业【{job.Key}】 触发器【{trigger.Key}】 下次执行时间【{df.LocalDateTime}】 " +
                                       $"执行时间间隔【{trigger.RepeatInterval.Seconds}】s 重复次数【{trigger.RepeatCount}】");


            //job = JobBuilder.Create<SimpleJob2>()
            //    .WithIdentity("job2","jobGroup")
            //    .Build();

            //trigger = (ISimpleTrigger)TriggerBuilder.Create()
            //    .WithIdentity("trigger2","triggerGroup1")
            //    .StartNow()
            //    .WithSimpleSchedule(x=>x.WithIntervalInSeconds(15).RepeatForever())
            //    .Build();

            //df = await scheduler.ScheduleJob(job, trigger);

            //ConsoleExtend.WriteLineRed($"作业【{job.Key}】 触发器【{trigger.Key}】 下次执行时间【{df.LocalDateTime}】 " +
            //    $"执行时间间隔【{trigger.RepeatInterval.Seconds}】s 重复次数【{trigger.RepeatCount}】");

            await scheduler.Start();

            Console.WriteLine("等待1分钟。。。");

            await Task.Delay(TimeSpan.FromMinutes(1));

            await scheduler.Shutdown();
        }
        public virtual void InitScheduler()
        {
            var section               = ServiceSection.GetSection("quartzservice");
            var jobConfigs            = section.Jobs;
            ISchedulerFactory factory = new StdSchedulerFactory();

            Scheduler = factory.GetScheduler();
            foreach (var j in jobConfigs)
            {
                var    jConfig = (j as ServiceJobElement);
                object jobObj  = Activator.CreateInstance(Type.GetType(jConfig.Type));
                JobObjectContainer.Set(jConfig.Name, jobObj);
                string jobName     = jConfig.Name;
                string triggerName = jobName + "_trigger";
                string cron        = jConfig.Cron;
                var    job         = JobBuilder.Create <DefaultJob>()
                                     .WithIdentity(jobName, "jobgroup")
                                     .RequestRecovery(true).Build();
                ITrigger trigger;

                if (string.IsNullOrEmpty(cron))
                {
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("triggergroup", triggerName)
                              .StartAt(DateTimeOffset.Now)
                              .Build();
                }
                else
                {
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("localTrigger", triggerName)
                              .StartAt(DateTimeOffset.Now)
                              .WithCronSchedule(cron)
                              .Build();
                }

                if (!Scheduler.CheckExists(job.Key))
                {
                    Scheduler.ScheduleJob(job, trigger);
                }
                Scheduler.ListenerManager.AddJobListener(new DefaultJobListener(), KeyMatcher <JobKey> .KeyEquals(job.Key));
            }
            Scheduler.ListenerManager.AddSchedulerListener(new DefaultSchedulerListener(this));
        }
Exemple #15
0
        public void Legacy_wire_data_can_run_with_latest_job_code()
        {
            ScheduleKey      key              = new ScheduleKey(Guid.NewGuid(), Name, Group);
            Command          command          = new SuccessCommand("1232");
            ExecutionOptions executionOptions = new ExecutionOptions(DateTime.Now.AddSeconds(1), typeof(ScheduledCommandSuccessfullyProcessed));

            var serializedCommand = SerializeAsLegacy(command);
            var serializedKey     = SerializeAsLegacy(key);
            var serializedOptions = SerializeAsLegacy(executionOptions);

            var jobDataMap = new JobDataMap
            {
                { QuartzJob.CommandKey, serializedCommand },
                { QuartzJob.ScheduleKey, serializedKey },
                { QuartzJob.ExecutionOptionsKey, serializedOptions }
            };

            var legacyJob = QuartzJob.CreateJob(key, jobDataMap);

            var listener = new CallbackJobListener();

            _quartzScheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(legacyJob.Key));
            var task = listener.TaskFinish.Task;

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(legacyJob.Key.Name, legacyJob.Key.Group)
                          .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow()
                                              .WithRepeatCount(0))
                          .StartAt(DateTimeOffset.Now.AddMilliseconds(200))
                          .Build();

            _quartzScheduler.ScheduleJob(legacyJob, trigger);

            if (!task.Wait(TimeSpan.FromSeconds(10000)))
            {
                Assert.Fail("Job execution timed out");
            }

            if (task.Result.Item2 != null)
            {
                Assert.Fail("Job threw an exception", task.Result.Item2);
            }
        }
Exemple #16
0
        /// <summary>
        /// Creador del servicio de Banners
        /// </summary>
        public BannerService()
        {
            cLogger.Info("Iniciando BannerService");

            iScheduler = StdSchedulerFactory.GetDefaultScheduler();

            iUpdateBannerJobKey = new JobKey("UBJK");

            iUpdateBannerJob = JobBuilder.Create <UpdateBannerJob>()
                               .WithIdentity(iUpdateBannerJobKey)
                               .Build();

            iScheduler.Start();
            iScheduler.ListenerManager.AddJobListener(this, (KeyMatcher <JobKey> .KeyEquals <JobKey>(iUpdateBannerJobKey)));

            cLogger.Info("Iniciando UpdateBanner Job");

            StartUpdateBannerJob(DateTime.Now);
        }
        static void Main()
        {
            HostFactory.Run(c =>
            {
                c.UseNinject(new SampleModule());

                c.Service <SampleService>(s =>
                {
                    // Topshelf.Quartz (Optional) - Construct service using Ninject
                    s.ConstructUsingNinject();

                    s.WhenStarted((service, control) => service.Start());
                    s.WhenStopped((service, control) => service.Stop());

                    // Topshelf.Quartz.Ninject (Optional) - Construct IJob instance with Ninject
                    s.UseQuartzNinject();

                    // Schedule a job to run in the background every 5 seconds.
                    // The full Quartz Builder framework is available here.
                    s.ScheduleQuartzJob(q =>
                                        q.WithJob(() =>
                                                  JobBuilder.Create <SampleJob>().Build())
                                        .AddTrigger(() =>
                                                    TriggerBuilder.Create()
                                                    .WithSimpleSchedule(builder => builder.WithIntervalInSeconds(5).RepeatForever()).Build())
                                        .WithJobListener(() =>
                    {
                        return(new QuartzJobListenerConfig(
                                   new SimpleJobListener(),
                                   KeyMatcher <JobKey> .KeyEquals(new JobKey("sample"))));
                    })
                                        .WithTriggerListener(() =>
                    {
                        return(new QuartzTriggerListenerConfig(
                                   new SimpleTriggerListener(),
                                   KeyMatcher <TriggerKey> .KeyEquals(new TriggerKey("sample"))));
                    })
                                        .WithScheduleListener(() => new SimpleScheduleListener())
                                        );
                });
            });
        }
Exemple #18
0
        public async Task ScheduleAfterDelay(IScheduler scheduler)
        {
            var listener = new
                           RepeatAfterCompletionJobListener(2);

            scheduler.ListenerManager.AddJobListener
                (listener, KeyMatcher <JobKey> .KeyEquals(new JobKey("re", "group1")));

            var job = JobBuilder.Create <SimpleJob>()
                      .WithIdentity("re", "group1")
                      .Build();

            // Schedule the job to start in 5 seconds to give the service time to initialise
            var trigger = TriggerBuilder.Create()
                          .WithIdentity("trigger_re", "group1")
                          .StartNow()
                          .Build();

            await scheduler.ScheduleJob(job, trigger);
        }
        /// <summary>
        /// Creador del servicio de campañas
        /// </summary>
        public CampaignService()
        {
            cLogger.Info("Iniciando CampaignService");

            iCampaignList = new List <Campaign>()
            {
            };
            iNewCampaignList = new List <Campaign>()
            {
            };

            iScheduler = StdSchedulerFactory.GetDefaultScheduler();

            iChangeImageJobKey     = new JobKey("CIJK");
            iUpdateCampaignsJobKey = new JobKey("UCJK");

            //Creacion de los jobs
            iChangeImageJob = JobBuilder.Create <ChangeImageJob>()
                              .WithIdentity(iChangeImageJobKey)
                              .Build();

            iUpdateCampaignsJob = JobBuilder.Create <UpdateCampaignsJob>()
                                  .WithIdentity(iUpdateCampaignsJobKey)
                                  .Build();

            iScheduler.Start();
            //Agrega este objeto como listener a los jobs anteriores
            iScheduler.ListenerManager.AddJobListener(this, OrMatcher <JobKey> .Or(KeyMatcher <JobKey> .KeyEquals <JobKey>(iChangeImageJobKey), KeyMatcher <JobKey> .KeyEquals <JobKey>(iUpdateCampaignsJobKey)));

            iUpdateAvailable = false;
            iUpdateDone      = false;

            iActualImage    = -1;
            iActualCampaign = 0;

            cLogger.Info("Iniciando CampaignService Jobs");

            //Se inician los jobs correspondientes, que luego se auto reinician
            StartUpdateCampaignsJob(DateTime.Now);
            StartChangeImageJob(CampaignService.DEFAULT_CHANGE_IMAGE_TIME);
        }
        public void Start()
        {
            logger.Info("Scheduler is running...");
            if (scheduler == null || scheduler.IsShutdown)
            {
                scheduler = new StdSchedulerFactory().GetScheduler();
            }

            JobKey     jobKey    = new JobKey(JOB_NAME, GROUP_NAME);
            IJobDetail jobDetail = JobBuilder.Create <CheckingUploadJob>().WithIdentity(jobKey).Build();

            ITrigger trigger = TriggerBuilder.Create().WithIdentity(TRIGGER_NAME, GROUP_NAME).StartNow()
                               .WithSimpleSchedule(a => a.WithIntervalInMinutes(10).RepeatForever()).Build();

            scheduler.ScheduleJob(jobDetail, trigger);

            CheckingUploadJobListener jobListener = new CheckingUploadJobListener(JOB_LISTENER_NAME);

            scheduler.ListenerManager.AddJobListener(jobListener, KeyMatcher <JobKey> .KeyEquals(jobKey));
            scheduler.Start();
        }
Exemple #21
0
        private static async Task InstanceForOneJob(MyJobListener myJobListener, StdSchedulerFactory factory)
        {
            IScheduler sched = await factory.GetScheduler();

            await sched.Start();

            IJobDetail job = JobBuilder.Create <DumbJob>().WithIdentity("myJob")
                             .UsingJobData("jobSays", "Hello World!")
                             .UsingJobData("myFloatValue", 3.141f)
                             .Build();

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create().WithIdentity("trigger")
                                     .StartNow()
                                     .WithSimpleSchedule(x => x.WithIntervalInSeconds(2)
                                                         .WithRepeatCount(10))
                                     .Build();

            //Adding a JobListener that is interested in a particular job:
            sched.ListenerManager.AddJobListener(myJobListener, KeyMatcher <JobKey> .KeyEquals(new JobKey("myJob")));

            await sched.ScheduleJob(job, trigger);
        }
Exemple #22
0
        private static async Task CreateJobSchedule(JobConfig jobAsset, Type type)
        {
            IJobDetail job = JobBuilder.Create(type)
                             .WithIdentity(jobAsset.Asset, jobAsset.Provider)
                             .UsingJobData("url", jobAsset.Url)
                             .UsingJobData("OrderNumber", jobAsset.OrderNumber)
                             .Build();

            // Trigger the job to run now, and then repeat every 3 seconds
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(jobAsset.Asset, jobAsset.Provider)
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInSeconds(jobAsset.TimeJobTimer)
                                                   .RepeatForever())
                               .Build();
            //// Tell quartz to schedule the job using our trigger

            await scheduler.ScheduleJob(job, trigger);

            scheduler.ListenerManager.AddJobListener(new RateJobListener(), KeyMatcher <JobKey> .KeyEquals(new JobKey(jobAsset.Asset, jobAsset.Provider)));
        }
Exemple #23
0
        public void JobListenerFired()
        {
            // Add Quartz (with 1 joblistener)
            Container.AddFacility <QuartzFacility>(f =>
            {
                f.JobListeners = new[]
                {
                    new JobListener(Container.Resolve <IJobListener>(),
                                    new IMatcher <JobKey>[] { KeyMatcher <JobKey> .KeyEquals(new JobKey("TestJob", "TestGroup")) })
                };

                f.Properties = QuartzProperties;
            });

            // Schedule Job
            ScheduleJob();
            Sleep(2);

            // Assert
            TestJobListener.Verify(m => m.JobWasExecuted(It.IsAny <IJobExecutionContext>(),
                                                         It.IsAny <JobExecutionException>(), It.IsAny <CancellationToken>()));
        }
Exemple #24
0
        private static async Task InitializationScheduler()
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            var job1 = JobBuilder.Create <HelloJob>()
                       .WithIdentity("Job1")
                       .StoreDurably(true).Build();

            var dinnerTime = DateBuilder.TodayAt(14, 33, 50);
            var trigger    = TriggerBuilder.Create()
                             .StartNow()
                             .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever())
                             .ForJob("Job1").Build();
            await scheduler.AddJob(job1, true);

            await scheduler.ScheduleJob(trigger);

            scheduler.ListenerManager.AddJobListener(
                new MyJobListener(),
                KeyMatcher <JobKey> .KeyEquals(new JobKey("Job1")));
            await scheduler.Start();
        }
Exemple #25
0
        public async Task InjectionPlan(IooinPlan plan)
        {
            Dictionary <Type, Type[]> jobs = plan.Jobs();

            foreach (var item in jobs)
            {
                var        instance = Activator.CreateInstance(item.Key);
                MethodInfo method   = (item.Key).GetMethod(plan.MethodName);
                string     jobName  = (item.Key).GetProperty("JobName")?.GetValue(instance).ToString() ?? "";


                IJobDetail job = JobBuilder.Create(typeof(BaseJob))
                                 .WithIdentity(jobName, plan.GroupName)
                                 .Build();

                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                         .WithIdentity($"{plan.GroupName}_{jobName}_trigger")
                                         .StartAt(plan.StartTime)
                                         .EndAt(plan.EndTime)
                                         .ForJob(jobName, plan.GroupName)
                                         .TriggerFrequency(plan)
                                         .Build();



                JobListener listener = new JobListener
                {
                    Name   = jobName,
                    Action = () => method.Invoke(instance, null)
                };

                IMatcher <JobKey> matcher = KeyMatcher <JobKey> .KeyEquals(job.Key);

                scheduler.ListenerManager.AddJobListener(listener, matcher);

                await scheduler.ScheduleJob(job, trigger);
            }
        }
Exemple #26
0
        public Service()
        {
            scheduler = StdSchedulerFactory.GetDefaultScheduler();


            index    = 1;
            newIndex = 1;
            updDisp  = false;
            updDone  = false;

            intervalJobKey        = new JobKey("iJK");
            anotherIntervalJobKey = new JobKey("aIJK");



            scheduler.Start();


            scheduler.ListenerManager.AddJobListener(this, OrMatcher <JobKey> .Or(KeyMatcher <JobKey> .KeyEquals <JobKey>(intervalJobKey), KeyMatcher <JobKey> .KeyEquals <JobKey>(anotherIntervalJobKey)));

            startIntervalJob(1);
            startAnotherIntervalJob(5);
        }
Exemple #27
0
        /// <summary>
        ///     开启job
        /// </summary>
        /// <param name="jobParam">job执行参数</param>
        /// <param name="onceJob">是否执行计划外的任务</param>
        /// <returns></returns>
        public bool StartJob(JobMeta jobParam, bool onceJob = false)
        {
            try
            {
                var triggerKey = onceJob ? UtilsFunc.GenTriggerKey(jobParam.JobName) : GetTriggerKey();
                var trigger    = GenTrigger(triggerKey, jobParam.StartTime, jobParam.Interval, jobParam.CronExpression,
                                            onceJob);
                if (trigger == null)
                {
                    JobLogHelper.Error(
                        $"创建{jobParam.JobName}的trigger失败,参数为{onceJob},{jobParam.StartTime},{jobParam.Interval},{jobParam.CronExpression}",
                        null, nameof(StartJob));
                    return(false);
                }

                var jobkey = onceJob ? UtilsFunc.GenJobKey(jobParam.JobName) : GetJobKey();
                var job    = JobBuilder.Create <T>()
                             .WithIdentity(jobkey)
                             .Build();

                job.SetJobName(jobParam.JobName);
                job.SetJobCode(jobParam.JobCode);
                job.SetOnceJobFlag(onceJob);
                job.SetDepJobs(jobParam.DepJobs);
                job.SetJobRunParams(jobParam.RunParams);
                job.SetAutoClose(jobParam.AutoClose);
                job.SetIsDoNotice(jobParam.IsDoNotice);

                ScheduleModConfig.Instance.DefaultScheduler.ScheduleJob(job, trigger);

                var jobListener = new LT();
                if (onceJob)
                {
                    jobListener.SetName(UtilsFunc.GenListenerName(jobParam.JobName));
                }
                ScheduleModConfig.Instance.DefaultScheduler.ListenerManager.AddJobListener(jobListener,
                                                                                           KeyMatcher <JobKey> .KeyEquals(jobkey));
                ScheduleModConfig.Instance.DefaultScheduler.ListenerManager.AddTriggerListener(jobListener,
                                                                                               KeyMatcher <TriggerKey> .KeyEquals(triggerKey));
                if (jobParam.State == JobStateEnum.Pause)
                {
                    ScheduleModConfig.Instance.DefaultScheduler.PauseJob(jobkey);
                }

                return(true);
            }
            catch (Exception ex)
            {
                JobLogHelper.Error(ex.Message, ex, nameof(StartJob));
                return(false);
            }
        }
        /// <summary>
        /// 定时任务开始
        /// </summary>
        /// <param name="logBuilder"></param>
        public static void StartJob()
        {
            Logger.Info("定时任务读取开始");
            ISchedulerFactory sf = new Quartz.Impl.StdSchedulerFactory();

            ServiceHelper._sched = sf.GetScheduler();
            int jobCounter     = 0;
            var currentService = ServiceHelper.CurrentWinService;

            if (currentService == null)
            {
                Logger.Error(null, $"找不到【{ServiceHelper.CurrentServiceName}】的配置");
                return;
            }
            foreach (var quartzJob in currentService.QuartzJob.JobItemList)
            {
                //配置检查
                if (string.IsNullOrWhiteSpace(quartzJob.JobKey) || string.IsNullOrWhiteSpace(quartzJob.Assembly) || string.IsNullOrWhiteSpace(quartzJob.QuartzCron))
                {
                    Logger.Error(null, $"QuartzJob.JobItem的JobKey,Assembly和QuartzCron不能为空. JobKey:{quartzJob.JobKey}, Assembly:{quartzJob.Assembly}, QuartzCron:{quartzJob.QuartzCron}");
                    continue;
                }

                //二选一
                if (string.IsNullOrWhiteSpace(quartzJob.ClassName) && string.IsNullOrWhiteSpace(quartzJob.MethodName))
                {
                    Logger.Error(null, $"QuartzJob.JobItem的JobKey={quartzJob.JobKey}的ClassName或MethodName不能为空. ClassName:{quartzJob.ClassName}, MethodName:{quartzJob.MethodName}");
                    continue;
                }

                try
                {
                    //如果执行方法不为空,则认为是没有继承Quartz.IJob
                    if (!string.IsNullOrEmpty(quartzJob.MethodName))
                    {
                        //如果执行的方法名不为空
                        var iIndex = quartzJob.MethodName.LastIndexOf(".");
                        quartzJob.ClassName  = quartzJob.MethodName.Substring(0, iIndex);  //将方法名给到类名
                        quartzJob.MethodName = quartzJob.MethodName.Substring(iIndex + 1); //留下方法名
                    }

                    Assembly assembly = ServiceHelper.GetAssembly(quartzJob.Assembly);
                    var      job      = assembly.CreateInstance(quartzJob.ClassName, false);

                    if (currentService.QuartzJob.JobItemList.Where(p => p.JobKey == quartzJob.JobKey).Count() > 1)
                    {
                        throw new Exception($"【{quartzJob.JobKey}】出现重复的JobKey");
                    }

                    #region 指定执行方法的处理与验证

                    if (!string.IsNullOrEmpty(quartzJob.MethodName))
                    {
                        //如果MethodName不为空,则启动本系统定时任务执行MethodName
                        if (job == null)
                        {
                            throw new Exception($"未能实例化对象:{quartzJob.ClassName}");
                        }
                        Type type       = job.GetType();
                        var  methodInfo = type.GetMethod(quartzJob.MethodName);
                        if (methodInfo == null)
                        {
                            throw new Exception($"不存在方法名:{quartzJob.ClassName}.{quartzJob.MethodName}");
                        }
                        object[] arrParam = null;
                        if (!string.IsNullOrEmpty(quartzJob.Parameters))
                        {
                            var arr = quartzJob.Parameters.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            if (arr.Length > 0)
                            {
                                arrParam = arr.ToArray();
                            }
                        }
                        CommonJob.AddJob(quartzJob.JobKey, job, methodInfo, arrParam);

                        //完成后,实例化成CommonJob
                        job = new CommonJob();
                    }
                    else
                    {
                        //否则,校验ClassName是否继承了IJob
                        if (!(job is IJob))
                        {
                            throw new Exception(string.Format("{0},没有继承Quartz.IJob", quartzJob.ClassName));
                        }
                    }

                    #endregion

                    //加载Job
                    var jobKey    = new JobKey(quartzJob.JobKey, ServiceHelper.TriggerGrouopName);
                    var jobDetail = JobBuilder.Create(job.GetType()).UsingJobData("Parameters", quartzJob.Parameters).WithIdentity(jobKey).Build();
                    var jobTrig   = new CronTriggerImpl(quartzJob.JobKey + "Trigger", ServiceHelper.TriggerGrouopName, quartzJob.QuartzCron);
                    ServiceHelper._sched.ScheduleJob(jobDetail, jobTrig);
                    jobCounter++;

                    //添加适配器(可以利用适配器添加监听器)
                    var matcher = KeyMatcher <JobKey> .KeyEquals(jobDetail.Key);

                    matcherList.Add(matcher);
                    Logger.Info($"读取成功. JobKey:{quartzJob.JobKey}");
                }
                catch (Exception ex)
                {
                    string msg = $"读取失败. JobKey:{quartzJob.JobKey}";
                    Logger.Error(ex, msg);
                    throw ex;
                }
            }
            Logger.Info("定时任务读取完成");
            if (jobCounter > 0)
            {
                ServiceHelper._sched.Start();
            }
        }
 /// <summary>
 /// Add <paramref name="listner"/> for a given job <paramref name="key"/>
 /// </summary>
 /// <param name="scheduler"></param>
 /// <param name="listner"></param>
 /// <param name="key"></param>
 public static void AddListner(this IScheduler scheduler, IJobListener listner, JobKey key)
 {
     scheduler.ListenerManager.AddJobListener(listner, KeyMatcher <JobKey> .KeyEquals(key));
 }
Exemple #30
0
        private static async Task Start(IHosSchedule schedule)
        {
            JobDataMap map = new JobDataMap
            {
                new KeyValuePair <string, object> ("instance", schedule),
            };
            string jobKey = schedule.Main.Id.ToString();

            try
            {
                IJobDetail job = JobBuilder.Create().OfType(schedule.GetQuartzJobType()).WithIdentity(jobKey).UsingJobData(map).Build();

                //添加监听器
                var listener = new JobRunListener(jobKey);
                listener.OnSuccess += StartedEvent;
                _scheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(new JobKey(jobKey)));

                ITrigger trigger = GetTrigger(schedule.Main);
                await _scheduler.ScheduleJob(job, trigger, schedule.CancellationTokenSource.Token);

                using (var scope = new Core.ScopeDbContext())
                {
                    var db   = scope.GetDbContext();
                    var task = db.Schedules.FirstOrDefault(x => x.Id == schedule.Main.Id);
                    if (task != null)
                    {
                        task.NextRunTime = TimeZoneInfo.ConvertTimeFromUtc(trigger.GetNextFireTimeUtc().Value.UtcDateTime, TimeZoneInfo.Local);
                        await db.SaveChangesAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SchedulerException(ex);
            }
            LogHelper.Info($"任务[{schedule.Main.Title}]启动成功!", schedule.Main.Id);

            _ = Task.Run(async() =>
            {
                while (true)
                {
                    if (schedule.RunnableInstance == null)
                    {
                        break;
                    }
                    var log = schedule.RunnableInstance.ReadLog();
                    if (log != null)
                    {
                        LogManager.Queue.Write(new SystemLogEntity
                        {
                            Category   = log.Category,
                            Message    = log.Message,
                            ScheduleId = log.ScheduleId,
                            Node       = log.Node,
                            StackTrace = log.StackTrace,
                            TraceId    = log.TraceId,
                            CreateTime = log.CreateTime
                        });
                    }
                    else
                    {
                        await Task.Delay(3000);
                    }
                }
            });
        }