private void SetNextTrigger(string id, ITrigger trigger, SchedulerCallback callback)
        {
            var milliSeconds = GetMilliSecondsToNextTrigger(trigger);

            bool isNotIntermediateCallback = true;
            long max = int.MaxValue * 2L;
            if (milliSeconds > max)
            {
                isNotIntermediateCallback = false;
                milliSeconds = max;
            }

            TimerCallback timerCallback = s =>
            {
                if (TimerIsNotCancelled(id))
                {
                    if (isNotIntermediateCallback)
                    {
                        InvokeCallbackAndSetNextTrigger(id, trigger, callback);
                    }
                    else
                    {
                        SetNextTrigger(id, trigger, callback);
                    }
                }
            };

            timers[id] = new System.Threading.Timer(timerCallback, null, milliSeconds, Timeout.Infinite);
        }
Esempio n. 2
0
 ///////////////////////////////////////////////////////////////////////
 public void Add(ITrigger trigger)
 {
     lock (_triggers) {
         trigger.Fire += SubTrigger_OnFire;
         _triggers.Add(trigger);
     }
 }
Esempio n. 3
0
 public ProjectIntegrator(ITrigger trigger, IIntegratable integratable, IProject project)
 {
     _trigger = trigger;
     _project = project;
     _integratable = integratable;
     this.resultManager = project.IntegrationResultManager;
 }
 public override void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
 {
     Log.TraceFormat("Trigger complete for job {0} with scheduler instruction {1}",
         context.JobDetail.JobType,
         triggerInstructionCode
     );
 }
Esempio n. 5
0
        public static TriggerDetailDto Create(ITrigger trigger, ICalendar calendar)
        {
            var simpleTrigger = trigger as ISimpleTrigger;
            if (simpleTrigger != null)
            {
                return new SimpleTriggerDetailDto(simpleTrigger, calendar);
            }
            var cronTrigger = trigger as ICronTrigger;
            if (cronTrigger != null)
            {
                return new CronTriggerDetailDto(cronTrigger, calendar);
            }
            var calendarIntervalTrigger = trigger as ICalendarIntervalTrigger;
            if (calendarIntervalTrigger != null)
            {
                return new CalendarIntervalTriggerDetailDto(calendarIntervalTrigger, calendar);
            }
            var dailyTimeIntervalTrigger = trigger as IDailyTimeIntervalTrigger;
            if (dailyTimeIntervalTrigger != null)
            {
                return new DailyTimeIntervalTriggerDetailDto(dailyTimeIntervalTrigger, calendar);
            }

            return new TriggerDetailDto(trigger, calendar);
        }
Esempio n. 6
0
 public void RemoveTrigger(string authKey, ITrigger trigger)
 {
     var profile = _profileRepository.GetProfile(authKey);
     var triggerToRemove = profile.Triggers.Single(x => x.Id == trigger.Id);
     profile.Triggers.Remove(triggerToRemove);
     _profileRepository.Update(profile);
 }
 public override void TriggerFired(ITrigger trigger, IJobExecutionContext context)
 {
     Log.DebugFormat("Trigger fired for job: {0} trigger key: {1}",
         context.JobDetail.JobType,
         trigger.Key.Name
     );
 }
Esempio n. 8
0
 public void AddTrigger(ITrigger trigger)
 {
     if (trigger != null)
     {
         this.triggers.Add(trigger);
     }
 }
Esempio n. 9
0
 public void UpdateTrigger(string authKey, ITrigger trigger)
 {
     var profile = _profileRepository.GetProfile(authKey);
     var index = profile.Triggers.IndexOf(profile.Triggers.Single(x => x.Id == trigger.Id));
     profile.Triggers[index] = trigger;
     _profileRepository.Update(profile);
 }
        public ConditionalTrigger WithTrigger(ITrigger trigger)
        {
            if (trigger == null) throw new ArgumentNullException(nameof(trigger));

            trigger.Attach(ForwardTriggerEvent);
            return this;
        }
Esempio n. 11
0
 public TriggerChoice()
 {
     InitializeComponent();
     CreateButton("Simple", () => Result = new SimpleTrigger());
     CreateButton("Regex", () => Result = new RegexTrigger());
     CreateButton("Action Queue", () => Result = new ActionQueueTrigger());
 }
Esempio n. 12
0
 /// <summary>
 /// Initializes a new instance of the AlarmBase class.
 /// </summary>
 /// <param name="action">Alarm action that should be triggered</param>
 /// <param name="trigger">Trigger for this alarm</param>
 protected AlarmBase(AlarmAction action, ITrigger trigger)
     : base(VersitObjectType.VALARM)
 {
     this.Fields.Add(new Property<AlarmAction>("ACTION", action));
     this.Fields.Add(new Duration("DURATION"));
     this.Fields.Add(trigger);
 }
Esempio n. 13
0
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// has fired, it's associated <see cref="IJobDetail" />
        /// has been executed, and it's <see cref="IOperableTrigger.Triggered" /> method has been
        /// called.
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        /// <param name="triggerInstructionCode"></param>
        public void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            Logger.InfoFormat("TriggerComplete: {0}, {1}", trigger.Key.Name, trigger.Key.Group);

            var auditLog = GetAuditLog(trigger, "TriggerComplete", context);
            _persistanceStore.InsertAuditLog(auditLog);
        }
Esempio n. 14
0
        /// <summary>
        /// Called by the Scheduler when a <see cref="ITrigger" /> has misfired.
        /// </summary>
        /// <param name="trigger"></param>
        public void TriggerMisfired(ITrigger trigger)
        {
            Logger.InfoFormat("TriggerMisfired: {0}, {1}", trigger.Key.Name, trigger.Key.Group);

            var auditLog = GetAuditLog(trigger, "TriggerMisfired");
            _persistanceStore.InsertAuditLog(auditLog);
        }
Esempio n. 15
0
        /// <summary>
        /// Called by the Scheduler when a <see cref="ITrigger" /> has fired, 
        /// and it's associated JobDetail is about to be executed.
        /// </summary>
        /// <param name="trigger"></param>
        /// <param name="context"></param>
        public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
        {
            Logger.InfoFormat("TriggerFired: {0}, {1}", trigger.Key.Name, trigger.Key.Group);

            var auditLog = GetAuditLog(trigger, "TriggerFired", context);
            _persistanceStore.InsertAuditLog(auditLog);
        }
        public bool MeetsCriteria(ITrigger trigger, object criteria)
        {
            Contract.Requires<ArgumentNullException>(trigger != null);
            Contract.Requires<ArgumentNullException>(criteria != null);

            throw new NotImplementedException();
        }
Esempio n. 17
0
        public ScheduleTrigger(TaskState state, ITrigger trigger, IDev2TaskService service, ITaskServiceConvertorFactory factory)
        {
            _service = service;
            _factory = factory;
            State = state;
            Trigger = trigger;

        }
Esempio n. 18
0
 public Task<bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
 {
     if (fireCount >= 3)
     {
         return Task.FromResult(true);
     }
     return Task.FromResult(false);
 }
Esempio n. 19
0
 public bool VetoJobExecution(ITrigger trigger, IJobExecutionContext context)
 {
     if (fireCount >= 3)
     {
         return true;
     }
     return false;
 }
        public static IAction OnTrigger(this IAction action, ITrigger trigger)
        {
            if (action == null) throw new ArgumentNullException(nameof(action));
            if (trigger == null) throw new ArgumentNullException(nameof(trigger));

            trigger.Attach(action);
            return action;
        }
Esempio n. 21
0
 internal JobExecutionContext(IScheduler scheduler, IJob job, ITrigger trigger, DateTimeOffset time, CancellationToken cancellationToken)
 {
     _scheduler = scheduler;
     _job = job;
     _trigger = trigger;
     _time = time;
     _cancellationToken = cancellationToken;
 }
Esempio n. 22
0
        /// <summary>
        /// Registers the trigger.
        /// </summary>
        /// <param name="trigger">The trigger.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="trigger"/> is <c>null</c>.</exception>
        public void RegisterTrigger(ITrigger trigger)
        {
            Argument.IsNotNull("trigger", trigger);

            //_triggers.Add(trigger);

            TriggerLoaded.SafeInvoke(this, new TriggerEventArgs(trigger));
        }
Esempio n. 23
0
        public SlideshowState(string name, OverlayPlugin manager, string folder, ITrigger next, ITrigger prev, IFeatureTransitionFactory transition, double fadeLengthMS)
            : base(name, manager)
        {
            AddTrigger(true, next);
            AddTrigger(false, prev);

            mTickListener = new Action(Core_Tick);
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the EmailAlarm class.
 /// </summary>
 /// <param name="trigger">Trigger for this alarm</param>
 /// <param name="summary">Text for the email subject</param>
 /// <param name="description">Text for the email body</param>
 public EmailAlarm(ITrigger trigger, string summary, string description)
     : base(AlarmAction.EMAIL, trigger)
 {
     this.Fields.Add(new Text("DESCRIPTION", description));
     this.Fields.Add(new Text("SUMMARY", summary));
     this.FieldCollections.Add("ATTENDEES", new VPropertyCollection<Attendee>());
     this.FieldCollections.Add("ATTACHMENTS", new VPropertyCollection<IAttachment>());
 }
Esempio n. 25
0
 internal Trigger(ITrigger iTrigger)
 {
     _v2Trigger = iTrigger;
     _ttype = iTrigger.Type;
     if (string.IsNullOrEmpty(_v2Trigger.StartBoundary))
     {
         StartBoundary = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local);
     }
 }
 public void Setup() {
     subTrigger1Mock = new DynamicMock(typeof(ITrigger));
     subTrigger2Mock = new DynamicMock(typeof(ITrigger));
     subTrigger1 = (ITrigger)subTrigger1Mock.MockInstance;
     subTrigger2 = (ITrigger)subTrigger2Mock.MockInstance;
     trigger = new MultipleTrigger();
     trigger.FirstTrigger = subTrigger1;
     trigger.SecondTrigger = subTrigger2;  
 }
		public void Setup()
		{
			subTrigger1Mock = new DynamicMock(typeof (ITrigger));
			subTrigger2Mock = new DynamicMock(typeof (ITrigger));
			subTrigger1 = (ITrigger) subTrigger1Mock.MockInstance;
			subTrigger2 = (ITrigger) subTrigger2Mock.MockInstance;
			trigger = new MultipleTrigger();
			trigger.Triggers = new ITrigger[] {subTrigger1, subTrigger2};
		}
Esempio n. 28
0
		/// <summary>
		///     Create a new task from given parameters
		/// </summary>
		/// <param name="name">Name for this task</param>
		/// <param name="enabled">Enable this task?</param>
		/// <param name="trigger">Trigger for this task</param>
		/// <param name="actions">Actions to be executed on trigger</param>
		public Task(string name, bool enabled, ITrigger trigger, List<IAction> actions)
		{
			Name = name;
			Enabled = enabled;
			Trigger = trigger;
			Actions = actions;

			Initialize();
		}
        /// <summary>
        ///     Entfernt einen Trigger aus dem laufenden System.
        /// </summary>
        /// <param name="trigger"></param>
        public void UnregisterTrigger(ITrigger trigger)
        {
            // Nur im Running-Mode erlaubt.
            if (Level.Mode != LevelMode.Running)
                throw new NotSupportedException("Level is not running");

            if (triggers.Contains(trigger))
                triggers.Remove(trigger);
        }
Esempio n. 30
0
 public EditTrigger(ITrigger trigger)
 {
     _trigger = trigger;
     InitializeComponent();
     Text = trigger.TypeAspect.CapitalizeEx() + " Trigger";
     trigger.Configs.ToList()
         .ForEach(x => SettingsLayout.Controls.Add(x.ControlHandle));
     trigger.GetNotifiers().ToList()
         .ForEach(AddConfigurator);
 }
Esempio n. 31
0
 public async Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
 {
     Debug.WriteLine($"Trigger fired : {trigger.Key.Name}");
 }
Esempio n. 32
0
 public void Add(ITrigger trigger)
 {
     _triggers.Add(trigger);
 }
Esempio n. 33
0
 public void agregarTask(IJobDetail job, ITrigger trigger)
 {
     scheduler.ScheduleJob(job, trigger);
 }
Esempio n. 34
0
        /// <summary>
        ///     Deserialize a string, and save it to this instance
        /// </summary>
        /// <param name="data">string to parse</param>
        /// <returns>returns this task object</returns>
        public Task Deserialize(string data)
        {
            Actions = new List <IAction>();
            string[] partedData = data.Split(new[] { ":;" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in partedData)
            {
                string[] dataFragments = s.Split(new[] { "::" }, StringSplitOptions.None);

                try
                {
                    switch (dataFragments[0])
                    {
                    case "TASK":
                        Name    = dataFragments[1];
                        Enabled = bool.Parse(dataFragments[2]);
                        break;

                    case "TRG":
                        foreach (ITrigger t in AllTriggers)
                        {
                            if (!t.Name.Equals(dataFragments[1]))
                            {
                                continue;
                            }

                            ITrigger trigger = (ITrigger)Activator.CreateInstance(t.GetType());
                            trigger.Load(dataFragments[2]);
                            Trigger = trigger;
                            break;                                     // we're done, we got the trigger. There can only be one trigger!
                        }
                        break;

                    case "ACT":
                        foreach (IAction a in AllActions)
                        {
                            if (!a.Name.Equals(dataFragments[1]))
                            {
                                continue;
                            }

                            IAction action = (IAction)Activator.CreateInstance(a.GetType());
                            action.Load(dataFragments[2]);
                            Actions.Add(action);
                            break;                                     // we're done, we got the trigger. There can only be one trigger!
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    Logger.Log(LogLevel.Warning, "Task", "Failed to parse task setting: " + dataFragments[0], e.Message);
                }
            }
            // in case 1 part wasn't loaded, fix (for UI purposes) and deactivate
            if (this.Trigger == null)
            {
                this.Trigger = new CurrentTimeTrigger {
                    Parameters = "00:00:00"
                };
                this.Enabled = false;
            }
            if (this.Actions == null)
            {
                this.Actions = new List <IAction>();
                this.Enabled = false;
            }
            if (string.IsNullOrEmpty(Name))
            {
                this.Name    = "UNNAMED_" + new Random().Next(1000, 9999);
                this.Enabled = false;
            }
            return(this);
        }
Esempio n. 35
0
 public virtual int CompareTo(ITrigger trigger)
 {
     return(this.Uid.CompareTo(trigger.Uid));
 }
Esempio n. 36
0
        private async Task TestMatchers(IScheduler scheduler)
        {
            await scheduler.Clear();

            IJobDetail job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "aaabbbccc").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create();
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("trig1", "aaabbbccc").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job1", "xxxyyyzzz").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            schedule = SimpleScheduleBuilder.Create();
            trigger  = TriggerBuilder.Create().WithIdentity("trig1", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create <NoOpJob>().WithIdentity("job2", "xxxyyyzzz").StoreDurably().Build();
            await scheduler.AddJob(job, true);

            schedule = SimpleScheduleBuilder.Create();
            trigger  = TriggerBuilder.Create().WithIdentity("trig2", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            await scheduler.ScheduleJob(trigger);

            var jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .AnyGroup());

            Assert.That(jkeys.Count, Is.EqualTo(3), "Wrong number of jobs found by anything matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("xxxyyyzzz"));

            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by equals matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("aaabbbccc"));

            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by equals matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("aa"));

            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by starts with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("xx"));

            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by starts with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("cc"));

            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by ends with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("zzz"));

            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by ends with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("bc"));

            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by contains with matcher");

            jkeys = await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("yz"));

            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by contains with matcher");

            var tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .AnyGroup());

            Assert.That(tkeys.Count, Is.EqualTo(3), "Wrong number of triggers found by anything matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("xxxyyyzzz"));

            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by equals matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("aaabbbccc"));

            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by equals matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("aa"));

            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by starts with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("xx"));

            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by starts with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("cc"));

            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by ends with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("zzz"));

            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by ends with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("bc"));

            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by contains with matcher");

            tkeys = await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("yz"));

            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by contains with matcher");
        }
Esempio n. 37
0
        private static async Task Main(string[] args)
        {
            // config Serilog logger
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .Enrich.FromLogContext()
                         .WriteTo.Console()
                         .WriteTo.File(new CompactJsonFormatter(), "./logs/msBackend/json/log.json", rollingInterval: RollingInterval.Day)
                         .WriteTo.File("./logs/msBackend/txt/log.txt", rollingInterval: RollingInterval.Day)
                         .CreateLogger();

            // config and setup Microsoft.Logging for Quartz
            using var loggerFactory = LoggerFactory.Create(builder => {
                builder
                .ClearProviders()
                .AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
                .AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning)
                .SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Debug)
                .AddSerilog(dispose: true);
            });

            Quartz.Logging.LogContext.SetCurrentLogProvider(loggerFactory);

            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            var configuration = builder.Build();

            MainOptions = new ModelScoutAPIOptions();

            configuration.GetSection(ModelScoutAPIOptions.ModelScout)
            .Bind(MainOptions);

            // Grab the Scheduler instance from the Factory
            StdSchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler          scheduler = await factory.GetScheduler();

            // define the job and tie it to our HelloJob class
            JobKey     mainJobKey = new JobKey("MainJob", "group1");
            IJobDetail job        = JobBuilder.Create <MainJob> ()
                                    .WithIdentity(mainJobKey)
                                    .Build();

            // Trigger the job to run now, and then repeat every 10 seconds
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .StartNow()
                               .Build();

            JobChainingJobListener chain = new JobChainingJobListener("testChain");

            chain.AddJobChainLink(mainJobKey, mainJobKey);

            // Tell quartz to schedule the job using our trigger
            await scheduler.ScheduleJob(job, trigger);

            scheduler.ListenerManager.AddJobListener(chain, GroupMatcher <JobKey> .AnyGroup());

            Console.WriteLine("Press any key to start the schedular");
            await Console.In.ReadLineAsync();

            // and start it off
            await scheduler.Start();

            // some sleep to show what's happening
            Console.WriteLine("Press any key to close the application");
            await Console.In.ReadLineAsync();

            // and last shut down the scheduler when you are ready to close your program
            await scheduler.Shutdown();

            Console.ReadKey();
        }
Esempio n. 38
0
 /// <summary>
 /// 错过触发时调用
 /// </summary>
 /// <param name="trigger">触发器</param>
 public void TriggerMisfired(ITrigger trigger)
 {
 }
Esempio n. 39
0
        /// <summary>
        /// Job完成时调用
        /// </summary>
        /// <param name="trigger">触发器</param>
        /// <param name="context">上下文</param>
        /// <param name="triggerInstructionCode"></param>
        public void TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode)
        {
            //TaskHelper.UpdateNextFireTime(trigger.JobKey.Name, TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local));

            _scheduleJobRepository.UpdateNextExecuteUtc(trigger.JobKey.Name, TimeZoneInfo.ConvertTimeFromUtc(context.NextFireTimeUtc.Value.DateTime, TimeZoneInfo.Local));
        }
Esempio n. 40
0
 /// <summary>
 /// Job执行时调用
 /// </summary>
 /// <param name="trigger">触发器</param>
 /// <param name="context">上下文</param>
 public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
 {
 }
Esempio n. 41
0
        private void ScheduleWorkflow(Workflow wf)
        {
            if (wf.IsEnabled)
            {
                if (wf.LaunchType == LaunchType.Startup)
                {
                    wf.Start();
                }
                else if (wf.LaunchType == LaunchType.Periodic)
                {
                    IDictionary <string, object> map = new Dictionary <string, object>();
                    map.Add("workflow", wf);

                    string     jobIdentity = "Workflow Job " + wf.Id;
                    IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                             .WithIdentity(jobIdentity)
                                             .SetJobData(new JobDataMap(map))
                                             .Build();

                    ITrigger trigger = TriggerBuilder.Create()
                                       .ForJob(jobDetail)
                                       .WithSimpleSchedule(x => x.WithInterval(wf.Period).RepeatForever())
                                       .WithIdentity("Workflow Trigger " + wf.Id)
                                       .StartNow()
                                       .Build();

                    var jobKey = new JobKey(jobIdentity);
                    if (Quartzcheduler.CheckExists(jobKey))
                    {
                        Quartzcheduler.DeleteJob(jobKey);
                    }

                    Quartzcheduler.ScheduleJob(jobDetail, trigger);
                }
                else if (wf.LaunchType == LaunchType.Cron)
                {
                    IDictionary <string, object> map = new Dictionary <string, object>();
                    map.Add("workflow", wf);

                    string     jobIdentity = "Workflow Job " + wf.Id;
                    IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                             .WithIdentity(jobIdentity)
                                             .SetJobData(new JobDataMap(map))
                                             .Build();

                    ITrigger trigger = TriggerBuilder.Create()
                                       .ForJob(jobDetail)
                                       .WithCronSchedule(wf.CronExpression)
                                       .WithIdentity("Workflow Trigger " + wf.Id)
                                       .StartNow()
                                       .Build();

                    var jobKey = new JobKey(jobIdentity);
                    if (Quartzcheduler.CheckExists(jobKey))
                    {
                        Quartzcheduler.DeleteJob(jobKey);
                    }

                    Quartzcheduler.ScheduleJob(jobDetail, trigger);
                }
            }
        }
Esempio n. 42
0
 public async Task TriggerMisfired(ITrigger trigger, CancellationToken cancellationToken = default(CancellationToken))
 {
     Debug.WriteLine($"Trigger miss-fired : {trigger.Key.Name}");
 }
        public async Task Run()
        {
            Console.WriteLine("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            var sched = await SchedulerBuilder.Create()
                        .WithName("PriorityExampleScheduler")
                        // Set thread count to 1 to force Triggers scheduled for the same time to
                        // to be ordered by priority.
                        .UseDefaultThreadPool(1)
                        .BuildScheduler();

            Console.WriteLine("------- Initialization Complete -----------");

            Console.WriteLine("------- Scheduling Jobs -------------------");

            IJobDetail job = JobBuilder.Create <TriggerEchoJob>()
                             .WithIdentity("TriggerEchoJob")
                             .Build();

            // All three triggers will fire their first time at the same time,
            // ordered by their priority, and then repeat once, firing in a
            // staggered order that therefore ignores priority.
            //
            // We should see the following firing order:
            // 1. Priority10Trigger15SecondRepeat
            // 2. Priority5Trigger10SecondRepeat
            // 3. Priority1Trigger5SecondRepeat
            // 4. Priority1Trigger5SecondRepeat
            // 5. Priority5Trigger10SecondRepeat
            // 6. Priority10Trigger15SecondRepeat

            // Calculate the start time of all triggers as 5 seconds from now
            DateTimeOffset startTime = DateBuilder.FutureDate(5, IntervalUnit.Second);

            // First trigger has priority of 1, and will repeat after 5 seconds
            ITrigger trigger1 = TriggerBuilder.Create()
                                .WithIdentity("Priority1Trigger5SecondRepeat")
                                .StartAt(startTime)
                                .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(5))
                                .WithPriority(1)
                                .ForJob(job)
                                .Build();

            // Second trigger has default priority of 5 (default), and will repeat after 10 seconds
            ITrigger trigger2 = TriggerBuilder.Create()
                                .WithIdentity("Priority5Trigger10SecondRepeat")
                                .StartAt(startTime)
                                .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(10))
                                .ForJob(job)
                                .Build();

            // Third trigger has priority 10, and will repeat after 15 seconds
            ITrigger trigger3 = TriggerBuilder.Create()
                                .WithIdentity("Priority10Trigger15SecondRepeat")
                                .StartAt(startTime)
                                .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(15))
                                .WithPriority(10)
                                .ForJob(job)
                                .Build();

            // Tell quartz to schedule the job using our trigger
            await sched.ScheduleJob(job, trigger1);

            await sched.ScheduleJob(trigger2);

            await sched.ScheduleJob(trigger3);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            Console.WriteLine("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // fire the triggers
            Console.WriteLine("------- Waiting 30 seconds... -------------");

            await Task.Delay(TimeSpan.FromSeconds(30));

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

            Console.WriteLine("------- Shutdown Complete -----------------");
        }
Esempio n. 44
0
 public Task JobScheduled(ITrigger trigger)
 {
     return(Task.WhenAll(listeners.Select(l => l.JobScheduled(trigger))));
 }
Esempio n. 45
0
        public async Task Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
            {
                if (clearJobs)
                {
                    await scheduler.Clear();
                }

                if (scheduleJobs)
                {
                    ICalendar cronCalendar    = new CronCalendar("0/5 * * * * ?");
                    ICalendar holidayCalendar = new HolidayCalendar();

                    // QRTZNET-86
                    ITrigger t = await scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));

                    Assert.IsNull(t);

                    AnnualCalendar cal = new AnnualCalendar();
                    await scheduler.AddCalendar("annualCalendar", cal, false, true);

                    IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                    calendarsTrigger.CalendarName = "annualCalendar";

                    JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                    await scheduler.ScheduleJob(jd, calendarsTrigger);

                    // QRTZNET-93
                    await scheduler.AddCalendar("annualCalendar", cal, true, true);

                    await scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);

                    await scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);

                    await scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);

                    await scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                    await scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);

                    await scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                    Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                    JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                    lonelyJob.Durable          = true;
                    lonelyJob.RequestsRecovery = true;
                    await scheduler.AddJob(lonelyJob, false);

                    await scheduler.AddJob(lonelyJob, true);

                    string schedId = scheduler.SchedulerInstanceId;

                    int count = 1;

                    JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = true;
                    IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                    trigger.JobDataMap.Add("key", "value");
                    trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                    trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                    await scheduler.ScheduleJob(job, trigger);

                    // check that trigger was stored
                    ITrigger persisted = await scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));

                    Assert.IsNotNull(persisted);
                    Assert.IsTrue(persisted is SimpleTriggerImpl);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                    trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    await scheduler.ScheduleJob(job, trigger);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                    ct.JobDataMap.Add("key", "value");
                    ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                    await scheduler.ScheduleJob(job, ct);

                    count++;
                    job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    // ask scheduler to re-Execute this job if it was in progress when
                    // the scheduler went down...
                    job.RequestsRecovery = (true);
                    DailyTimeIntervalTriggerImpl nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1), new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                    nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);

                    await scheduler.ScheduleJob(job, nt);

                    DailyTimeIntervalTriggerImpl nt2 = new DailyTimeIntervalTriggerImpl();
                    nt2.Key          = new TriggerKey("nth_trig2_" + count, schedId);
                    nt2.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                    nt2.JobKey       = job.Key;
                    await scheduler.ScheduleJob(nt2);

                    // GitHub issue #92
                    await scheduler.GetTrigger(nt2.Key);

                    // GitHub issue #98
                    nt2.StartTimeOfDay = new TimeOfDay(1, 2, 3);
                    nt2.EndTimeOfDay   = new TimeOfDay(2, 3, 4);

                    await scheduler.UnscheduleJob(nt2.Key);

                    await scheduler.ScheduleJob(nt2);

                    var triggerFromDb = (IDailyTimeIntervalTrigger)await scheduler.GetTrigger(nt2.Key);

                    Assert.That(triggerFromDb.StartTimeOfDay.Hour, Is.EqualTo(1));
                    Assert.That(triggerFromDb.StartTimeOfDay.Minute, Is.EqualTo(2));
                    Assert.That(triggerFromDb.StartTimeOfDay.Second, Is.EqualTo(3));

                    Assert.That(triggerFromDb.EndTimeOfDay.Hour, Is.EqualTo(2));
                    Assert.That(triggerFromDb.EndTimeOfDay.Minute, Is.EqualTo(3));
                    Assert.That(triggerFromDb.EndTimeOfDay.Second, Is.EqualTo(4));

                    job.RequestsRecovery = (true);
                    CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                        "calint_trig_" + count,
                        schedId,
                        DateTime.UtcNow.AddMilliseconds(300),
                        DateTime.UtcNow.AddMinutes(1),
                        IntervalUnit.Second,
                        8);
                    intervalTrigger.JobKey = job.Key;

                    await scheduler.ScheduleJob(intervalTrigger);

                    // bulk operations
                    var        info     = new Dictionary <IJobDetail, IReadOnlyCollection <ITrigger> >();
                    IJobDetail detail   = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                    ITrigger   simple   = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                    var        triggers = new HashSet <ITrigger>();
                    triggers.Add(simple);
                    info[detail] = triggers;

                    await scheduler.ScheduleJobs(info, true);

                    Assert.IsTrue(await scheduler.CheckExists(detail.Key));
                    Assert.IsTrue(await scheduler.CheckExists(simple.Key));

                    // QRTZNET-243
                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupContains("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupContains("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEndsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupStartsWith("a").DeepClone());

                    await scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("a").DeepClone());

                    await scheduler.Start();

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.PauseAll();

                    await scheduler.ResumeAll();

                    await scheduler.PauseJob(new JobKey("job_1", schedId));

                    await scheduler.ResumeJob(new JobKey("job_1", schedId));

                    await scheduler.PauseJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

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

                    await scheduler.ResumeJobs(GroupMatcher <JobKey> .GroupEquals(schedId));

                    await scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));

                    await scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                    await scheduler.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    var pausedTriggerGroups = await scheduler.GetPausedTriggerGroups();

                    Assert.AreEqual(1, pausedTriggerGroups.Count);

                    await Task.Delay(TimeSpan.FromSeconds(3));

                    await scheduler.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals(schedId));

                    Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                    Assert.IsNotNull(scheduler.GetMetaData());
                    Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                    var genericjobKey = new JobKey("genericJob", "genericGroup");
                    GenericJobType.Reset();
                    var genericJob = JobBuilder.Create <GenericJobType>()
                                     .WithIdentity(genericjobKey)
                                     .StoreDurably()
                                     .Build();

                    await scheduler.AddJob(genericJob, false);

                    genericJob = await scheduler.GetJobDetail(genericjobKey);

                    Assert.That(genericJob, Is.Not.Null);
                    await scheduler.TriggerJob(genericjobKey);

                    GenericJobType.WaitForTrigger(TimeSpan.FromSeconds(20));

                    Assert.That(GenericJobType.TriggeredCount, Is.EqualTo(1));
                    await scheduler.Standby();

                    CollectionAssert.IsNotEmpty(await scheduler.GetCalendarNames());
                    CollectionAssert.IsNotEmpty(await scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(schedId)));

                    CollectionAssert.IsNotEmpty(await scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                    Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                    await scheduler.DeleteCalendar("cronCalendar");

                    await scheduler.DeleteCalendar("holidayCalendar");

                    await scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));

                    await scheduler.DeleteJob(job.Key);

                    await scheduler.GetJobGroupNames();

                    await scheduler.GetCalendarNames();

                    await scheduler.GetTriggerGroupNames();

                    await TestMatchers(scheduler);
                }
            }
            finally
            {
                await scheduler.Shutdown(false);
            }
        }
Esempio n. 46
0
 public void TriggerComplete(ITrigger trigger,
                             IJobExecutionContext context,
                             SchedulerInstruction triggerInstructionCode)
 {
 }
Esempio n. 47
0
 public void AddTrigger(ITrigger trigger)
 {
     this.triggers.Add(trigger);
     this.bus.Publish(new MessageTriggerAddedToRemoteProcessEvent(this.Id, trigger.Id));
 }
Esempio n. 48
0
        /// <summary>
        /// Handles the Start event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Application_Start(object sender, EventArgs e)
        {
            if (System.Web.Hosting.HostingEnvironment.IsDevelopmentEnvironment)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Application_Start: {0}", DateTime.Now));
                HttpInternals.RockWebFileChangeMonitor();
            }

            // Check if database should be auto-migrated for the core and plugins
            bool autoMigrate = true;

            if (!Boolean.TryParse(ConfigurationManager.AppSettings["AutoMigrateDatabase"], out autoMigrate))
            {
                autoMigrate = true;
            }

            if (autoMigrate)
            {
                try
                {
                    Database.SetInitializer(new MigrateDatabaseToLatestVersion <Rock.Data.RockContext, Rock.Migrations.Configuration>());

                    // explictly check if the database exists, and force create it if doesn't exist
                    Rock.Data.RockContext rockContext = new Rock.Data.RockContext();
                    if (!rockContext.Database.Exists())
                    {
                        rockContext.Database.Initialize(true);
                    }
                    else
                    {
                        var migrator = new System.Data.Entity.Migrations.DbMigrator(new Rock.Migrations.Configuration());
                        migrator.Update();
                    }

                    // Migrate any plugins that have pending migrations
                    List <Type> configurationTypeList = Rock.Reflection.FindTypes(typeof(System.Data.Entity.Migrations.DbMigrationsConfiguration)).Select(a => a.Value).ToList();

                    foreach (var configType in configurationTypeList)
                    {
                        if (configType != typeof(Rock.Migrations.Configuration))
                        {
                            var config = Activator.CreateInstance(configType) as System.Data.Entity.Migrations.DbMigrationsConfiguration;
                            System.Data.Entity.Migrations.DbMigrator pluginMigrator = Activator.CreateInstance(typeof(System.Data.Entity.Migrations.DbMigrator), config) as System.Data.Entity.Migrations.DbMigrator;
                            pluginMigrator.Update();
                        }
                    }
                }
                catch (Exception ex)
                {
                    // if migrations fail, log error and attempt to continue
                    LogError(ex, null);
                }
            }
            else
            {
                // default Initializer is CreateDatabaseIfNotExists, but we don't want that to happen if automigrate is false, so set it to NULL so that nothing happens
                Database.SetInitializer <Rock.Data.RockContext>(null);
            }

            // Preload the commonly used objects
            LoadCacheObjects();

            // setup and launch the jobs infrastructure if running under IIS
            bool runJobsInContext = Convert.ToBoolean(ConfigurationManager.AppSettings["RunJobsInIISContext"]);

            if (runJobsInContext)
            {
                ISchedulerFactory sf;

                // create scheduler
                sf    = new StdSchedulerFactory();
                sched = sf.GetScheduler();

                // get list of active jobs
                ServiceJobService jobService = new ServiceJobService();
                foreach (ServiceJob job in jobService.GetActiveJobs().ToList())
                {
                    try
                    {
                        IJobDetail jobDetail  = jobService.BuildQuartzJob(job);
                        ITrigger   jobTrigger = jobService.BuildQuartzTrigger(job);

                        sched.ScheduleJob(jobDetail, jobTrigger);
                    }
                    catch (Exception ex)
                    {
                        // create a friendly error message
                        string message = string.Format("Error loading the job: {0}.  Ensure that the correct version of the job's assembly ({1}.dll) in the websites App_Code directory. \n\n\n\n{2}", job.Name, job.Assembly, ex.Message);
                        job.LastStatusMessage = message;
                        job.LastStatus        = "Error Loading Job";

                        jobService.Save(job, null);
                    }
                }

                // set up the listener to report back from jobs as they complete
                sched.ListenerManager.AddJobListener(new RockJobListener(), EverythingMatcher <JobKey> .AllJobs());

                // start the scheduler
                sched.Start();
            }

            // add call back to keep IIS process awake at night and to provide a timer for the queued transactions
            AddCallBack();

            RegisterFilters(GlobalConfiguration.Configuration.Filters);

            RegisterRoutes(RouteTable.Routes);

            Rock.Security.Authorization.Load();

            AddEventHandlers();

            new EntityTypeService().RegisterEntityTypes(Server.MapPath("~"));
            new FieldTypeService().RegisterFieldTypes(Server.MapPath("~"));

            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Esempio n. 49
0
        public override DependencyObject CreateTrigger(StyleSheet styleSheet, ITrigger trigger, Type targetType, DependencyObject styleResourceReferenceHolder)
        {
            if (trigger == null)
            {
                throw new ArgumentNullException(nameof(trigger));
            }

            if (trigger is Trigger)
            {
                var propertyTrigger = trigger as Trigger;
                var nativeTrigger   = new System.Windows.Trigger();

                var dependencyProperty = dependencyService.GetDependencyProperty(targetType, propertyTrigger.Property);
                if (dependencyProperty == null)
                {
                    throw new NullReferenceException($"Property '{propertyTrigger.Property}' may not be null (targetType '{targetType.Name}')!");
                }

                nativeTrigger.Property = dependencyProperty;
                nativeTrigger.Value    = dependencyService.GetDependencyPropertyValue(targetType, nativeTrigger.Property.Name, nativeTrigger.Property, propertyTrigger.Value);
                foreach (var styleDeclaration in propertyTrigger.StyleDeclarationBlock)
                {
                    var propertyInfo = typeNameResolver.GetDependencyPropertyInfo(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                    if (propertyInfo == null)
                    {
                        continue;
                    }
                    try
                    {
                        var value = typeNameResolver.GetPropertyValue(propertyInfo.DeclaringType, styleResourceReferenceHolder, propertyInfo.Name, styleDeclaration.Value, propertyInfo.Property, styleSheet.Namespaces);
                        if (value == null)
                        {
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = propertyInfo.Property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in propertyTrigger.EnterActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" enter action: {e.Message}");
                    }
                }
                foreach (var action in propertyTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in property trigger ""{propertyTrigger.Property} {propertyTrigger.Value}"" exit action: {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }
            else if (trigger is DataTrigger)
            {
                var dataTrigger   = trigger as DataTrigger;
                var nativeTrigger = new System.Windows.DataTrigger();

                string expression = null;
                if (typeNameResolver.IsMarkupExtension(dataTrigger.Binding))
                {
                    expression = typeNameResolver.CreateMarkupExtensionExpression(dataTrigger.Binding);
                }
                else
                {
                    expression = "{Binding " + dataTrigger.Binding + "}";
                }

                var binding = (System.Windows.Data.BindingBase)markupExtensionParser.ProvideValue(expression, null, styleSheet.Namespaces);
                nativeTrigger.Binding = binding;

                nativeTrigger.Value = GetBasicValue(dataTrigger);

                foreach (var styleDeclaration in dataTrigger.StyleDeclarationBlock)
                {
                    try
                    {
                        var propertyInfo = typeNameResolver.GetDependencyPropertyInfo(styleSheet.Namespaces, targetType, styleDeclaration.Property);
                        if (propertyInfo == null)
                        {
                            continue;
                        }

                        var value = typeNameResolver.GetPropertyValue(propertyInfo.DeclaringType, styleResourceReferenceHolder, propertyInfo.Name, styleDeclaration.Value, propertyInfo.Property, styleSheet.Namespaces);
                        if (value == null)
                        {
                        }

                        nativeTrigger.Setters.Add(new Setter {
                            Property = propertyInfo.Property, Value = value
                        });
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {styleDeclaration.Property}: {styleDeclaration.Value}"": {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.EnterActions)
                {
                    try
                    {
                        System.Windows.TriggerAction nativeTriggerAction = null;

                        nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.EnterActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" enter action: {e.Message}");
                    }
                }

                foreach (var action in dataTrigger.ExitActions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.ExitActions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in data trigger ""{dataTrigger.Binding} {dataTrigger.Value} - {action}"" exit action: {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }
            else if (trigger is EventTrigger)
            {
                var eventTrigger  = trigger as EventTrigger;
                var nativeTrigger = new System.Windows.EventTrigger();

                nativeTrigger.RoutedEvent = (RoutedEvent)TypeHelpers.GetFieldValue(targetType, eventTrigger.Event + "Event");
                foreach (var action in eventTrigger.Actions)
                {
                    try
                    {
                        var nativeTriggerAction = CreateTriggerAction(styleSheet, styleResourceReferenceHolder, action);

                        nativeTrigger.Actions.Add(nativeTriggerAction);
                    }
                    catch (Exception e)
                    {
                        styleSheet.Errors.Add($@"ERROR in event trigger ""{eventTrigger.Event} {action.Action}"": {e.Message}");
                    }
                }

                var serialized = SerializeObject(nativeTrigger);
                //serialized = $"pre XamlWriter.Save({nativeTrigger.GetType().Name})".Measure(() => XamlWriter.Save(nativeTrigger));

                Css.SetSerializedTrigger(nativeTrigger, serialized);

                return(nativeTrigger);
            }

            throw new NotSupportedException($"Trigger '{trigger.GetType().FullName}' is not supported!");
        }
Esempio n. 50
0
 public void TriggerFinalized(ITrigger trigger)
 {
     triggerFinalizedCount++;
     logger.Info("triggerFinalized " + trigger);
 }
Esempio n. 51
0
 public void Remove(ITrigger trigger)
 {
     _triggers.Remove(trigger);
 }
Esempio n. 52
0
 public void TriggerFired(ITrigger trigger, IJobExecutionContext context)
 {
     fireCount++;
     logger.Info("Trigger fired. count " + fireCount);
 }
Esempio n. 53
0
 public void JobScheduled(ITrigger trigger)
 {
 }
Esempio n. 54
0
 public async Task TriggerComplete(ITrigger trigger, IJobExecutionContext context, SchedulerInstruction triggerInstructionCode, CancellationToken cancellationToken = default(CancellationToken))
 {
     Debug.WriteLine($"Trigger completed : {trigger.Key.Name}");
 }
Esempio n. 55
0
 /// <summary>
 /// Tarkistaa onko triggeriä mäpätty mihinkään
 /// </summary>
 /// <param name="trigger"></param>
 /// <returns></returns>
 public bool HasMappings(ITrigger trigger)
 {
     return(MappingNames.ContainsKey(trigger.TriggerHash()));
 }
Esempio n. 56
0
        private void EditJob()
        {
            try
            {
                var jobName  = jobsDataGridView.SelectedRows[0].Cells["JobName"].Value.ToString();
                var jobGroup = jobsDataGridView.SelectedRows[0].Cells["JobGroup"].Value.ToString();
                var jobKey   = new JobKey(jobName, jobGroup);

                var scheduler = Scheduler.Instance.GetScheduler();
                if (scheduler == null)
                {
                    MessageBox.Show(Resources.No_active_scheduler, Resources.Missing_scheduler);
                    return;
                }

                var jobDetail  = scheduler.GetJobDetail(jobKey).Result;
                var jobTrigger = scheduler.GetTriggersOfJob(jobKey).Result.First();
                switch (jobDetail.JobType.FullName)
                {
                case SettingsConstants.DownloadJob:
                {
                    using DownloadJobV3 downloadForm = new DownloadJobV3
                          {
                              JobDetail = jobDetail,
                              Trigger   = jobTrigger
                          };

                    downloadForm.ShowDialog();

                    if (downloadForm.Cancelled && downloadForm.JobDetail == null && downloadForm.Trigger == null)
                    {
                        return;
                    }

                    scheduler.ScheduleJob(downloadForm.JobDetail, new HashSet <ITrigger> {
                            downloadForm.Trigger
                        }, true);

                    RefreshGrid();
                }
                break;

                case SettingsConstants.ExportJob:
                {
                    using ExportJobV3 exportForm = new ExportJobV3
                          {
                              JobDetail = jobDetail,
                              Trigger   = jobTrigger
                          };

                    exportForm.ShowDialog();

                    if (exportForm.Cancelled && exportForm.JobDetail == null && exportForm.Trigger == null)
                    {
                        return;
                    }

                    scheduler.ScheduleJob(exportForm.JobDetail, new HashSet <ITrigger> {
                            exportForm.Trigger
                        }, true);

                    RefreshGrid();
                }
                break;

                case SettingsConstants.UploadJob:
                    //find related processing job
                    var      processingJobName    = jobDetail.Key.Name + "-Processing monitor";
                    var      processingJobKey     = new JobKey(processingJobName, jobDetail.Key.Group);
                    var      processingJobDetail  = scheduler.GetJobDetail(processingJobKey).Result;
                    ITrigger processingJobTrigger = null;

                    if (processingJobDetail != null)
                    {
                        processingJobTrigger = scheduler.GetTriggersOfJob(processingJobKey).Result.First();
                    }
                    {
                        using UploadJobV3 uploadForm = new UploadJobV3
                              {
                                  UploadJobDetail = jobDetail,
                                  UploadTrigger   = jobTrigger
                              };
                        if ((processingJobDetail != null) && (processingJobTrigger != null))
                        {
                            uploadForm.ProcessingJobDetail = processingJobDetail;
                            uploadForm.ProcessingTrigger   = processingJobTrigger;
                        }

                        uploadForm.ShowDialog();

                        if (uploadForm.Cancelled && uploadForm.UploadJobDetail == null && uploadForm.UploadTrigger == null)
                        {
                            return;
                        }

                        scheduler.ScheduleJob(uploadForm.UploadJobDetail, new HashSet <ITrigger> {
                            uploadForm.UploadTrigger
                        }, true);

                        if ((uploadForm.ProcessingJobDetail != null) && (uploadForm.ProcessingTrigger != null))
                        {
                            scheduler.ScheduleJob(uploadForm.ProcessingJobDetail, new HashSet <ITrigger> {
                                uploadForm.ProcessingTrigger
                            }, true);
                        }

                        RefreshGrid();
                    }
                    break;

                case SettingsConstants.ImportJob:
                    //find related execution job
                    var      executionJobName    = jobDetail.Key.Name + "-Execution monitor";
                    var      executionJobKey     = new JobKey(executionJobName, jobDetail.Key.Group);
                    var      executionJobDetail  = scheduler.GetJobDetail(executionJobKey).Result;
                    ITrigger executionJobTrigger = null;

                    if (executionJobDetail != null)
                    {
                        executionJobTrigger = scheduler.GetTriggersOfJob(executionJobKey).Result.First();
                    }
                    {
                        using ImportJobV3 importForm = new ImportJobV3
                              {
                                  ImportJobDetail = jobDetail,
                                  ImportTrigger   = jobTrigger
                              };

                        if ((executionJobDetail != null) && (executionJobTrigger != null))
                        {
                            importForm.ExecutionJobDetail = executionJobDetail;
                            importForm.ExecutionTrigger   = executionJobTrigger;
                        }
                        importForm.ShowDialog();

                        if (importForm.Cancelled && importForm.ImportJobDetail == null && importForm.ImportTrigger == null)
                        {
                            return;
                        }

                        scheduler.ScheduleJob(importForm.ImportJobDetail, new HashSet <ITrigger> {
                            importForm.ImportTrigger
                        }, true);

                        if (importForm.ExecutionJobDetail != null && importForm.ExecutionTrigger != null)
                        {
                            scheduler.ScheduleJob(importForm.ExecutionJobDetail, new HashSet <ITrigger> {
                                importForm.ExecutionTrigger
                            }, true);
                        }
                        RefreshGrid();
                    }
                    break;

                default:
                    MessageBox.Show(Resources.This_type_of_job_is_not_supported_for_direct_editing);
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.Unexpected_error);
            }
        }
Esempio n. 57
0
 public static void AddSchedule <T>(JobServer <T> jobServer, ITrigger trigger, string jobName, string jobGroup) where T : IJob
 {
     jobServer.JobName  = jobName;
     jobServer.JobGroup = jobGroup;
     Scheduler.ScheduleJob(jobServer.CrateJob(), trigger);
 }
Esempio n. 58
0
 /// <summary>
 /// 添加任务
 /// </summary>
 public Task AddJob(IJobDetail jobDetail, ITrigger trigger, CancellationToken cancellation = default)
 {
     return(_scheduler.ScheduleJob(jobDetail, trigger, cancellation));
 }
Esempio n. 59
0
 public async Task <bool> VetoJobExecution(ITrigger trigger, IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(false);
 }
Esempio n. 60
0
 //注册触发器
 public void registerTrigger(ITrigger trigger)
 {
     m_triggerSystem.registerTrigger(trigger);
 }