Exemplo n.º 1
0
        public Task Execute(IJobExecutionContext context)
        {
            var jobData         = QuartzScheduler.GetJobDataConfiguration <MunicipalityCodeJobDataConfiguration>(context.JobDetail);
            var serviceProvider = context.Scheduler.Context.Get(QuartzScheduler.SERVICE_PROVIDER) as IServiceProvider;

            ExecuteInternal(unitOfWork =>
            {
                var content = Download(jobData.Url, GetKapaConfiguration(context)); // roughly 300k
                var downloadedMunicipalityCodes = Parse(content);

                var existingMunicipalityCodes = unitOfWork.CreateRepository <IMunicipalityRepository>()
                                                .All()
                                                .Include(a => a.MunicipalityNames).ThenInclude(b => b.Localization)
                                                .ToList();

                // add new postal codes and update existing
                var vmToEntity = serviceProvider.GetRequiredService <ITranslationViewModel>();
                vmToEntity.TranslateAll <VmJsonMunicipality, Municipality>(downloadedMunicipalityCodes, unitOfWork);

                // invalidate not exist postal codes
                var municipalityCodesToInvalidate = existingMunicipalityCodes.Where(em => !downloadedMunicipalityCodes.Select(a => a.MunicipalityCode).Contains(em.Code)).ToList();
                municipalityCodesToInvalidate.ForEach(m => m.IsValid = false);

                unitOfWork.Save(SaveMode.AllowAnonymous, userName: context.JobDetail.Key.Name);
            }, context);
            return(Task.CompletedTask);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Instantiates the scheduler.
        /// </summary>
        /// <param name="rsrcs">The resources.</param>
        /// <param name="qs">The scheduler.</param>
        /// <returns>Scheduler.</returns>
        protected override IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs)
        {
            var scheduler = base.Instantiate(rsrcs, qs);

            scheduler.JobFactory = _jobFactory;
            return(scheduler);
        }
Exemplo n.º 3
0
        public async Task <JsonResult> GetJobHistory()
        {
            int             count   = 0;
            QuartzScheduler context = new QuartzScheduler(quartzJobStoreSettings.QuartzConnectionString);

            var dataTableData = new DataTableData <QRTZ_JOB_HISTORY>();
            var gridData      = context.QRTZ_JOB_HISTORY.ToList();//new List<QRTZ_JOB_HISTORY>();


            PagingData pgData = new PagingData(Request.QueryString);


            Expression <Func <QRTZ_JOB_HISTORY, bool> > where = w => (
                w.JOB_NAME.Contains(pgData.Search ?? ""));

            /*   Expression<Func<Order, bool>> where = w => (
             *  w.OrderNumber != "");*/
            dataTableData.draw = pgData.Draw;


            //
            count = gridData.Count;

            gridData = await GetList(gridData.Where(d => d.JOB_NAME != "").AsQueryable().OrderByDescending(d => d.STARTDATE).ThenBy(d => d.JOB_NAME), pgData, where);

            dataTableData.data            = gridData;
            dataTableData.recordsFiltered = count;
            dataTableData.recordsTotal    = count;
            dataTableData.success         = true;

            return(Json(dataTableData, JsonRequestBehavior.AllowGet));
        }
        private void ScheduleExecuteActionJob(long entityId, AuditEntity auditEntity, AutomatedAction ac)
        {
            var scheduler = new QuartzScheduler(
                ConfigurationManager.AppSettings["QuartzServer"],
                Convert.ToInt32(ConfigurationManager.AppSettings["QuartzPort"]),
                ConfigurationManager.AppSettings["QuartzScheduler"]);

            IDictionary <string, object> map = new Dictionary <string, object>();

            map.Add("EntityId", entityId.ToString());
            map.Add("EntityType", auditEntity.EntityType.Name);
            map.Add("AutomatedActionId", ac.Id.ToString());

            //get Type of Job
            Type type = Type.GetType("BaseEAM.Services.ExecuteActionJob, BaseEAM.Services");

            if (ac.TriggerType == (int?)ActionTriggerType.Immediately)
            {
                scheduler.ScheduleOneTimeJob(type, map);
            }
            else if (ac.TriggerType == (int?)ActionTriggerType.TimeBased)
            {
                scheduler.ScheduleOneTimeJob(type, map, ac.HoursAfter);
            }
        }
Exemplo n.º 5
0
        public Task SaveHistory(IJobExecutionContext context, string Status)
        {
            return(Task.Run(() =>
            {
                QuartzScheduler db = new QuartzScheduler(quartzJobStoreSettings.QuartzConnectionString);
                QRTZ_JOB_HISTORY history = new QRTZ_JOB_HISTORY();
                history.JOB_GROUP = context.JobDetail.Key.Group;
                history.SCHED_NAME = context.Scheduler.SchedulerName;
                history.JOB_NAME = context.JobDetail.Key.Name;
                history.STATUSDETAIL = Status;
                history.RECORDDATE = DateTime.Now;
                history.STARTDATE = context.FireTimeUtc.ToLocalTime().DateTime;
                history.ENDDATE = history.STARTDATE + context.JobRunTime;
                history.ISEXCEPTION = (Status != "Successful");
                history.TRIGGER_GROUP = context.Trigger.Key.Group;
                history.TRIGGER_NAME = context.Trigger.Key.Name;

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(memoryStream, context.JobDetail.JobDataMap);
                    history.JOB_DATA = memoryStream.ToArray();
                }
                IQuartzServiceJob job = (IQuartzServiceJob)context.JobInstance;
                history.LOGFILE = job.GetLogFile();
                db.QRTZ_JOB_HISTORY.InsertOnSubmit(history);
                db.SubmitChanges();
            }));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes the job execution context with given scheduler and bundle.
        /// </summary>
        /// <param name="sched">The scheduler.</param>
        /// <param name="cancellationToken">The cancellation instruction.</param>
        public virtual async Task Initialize(
            QuartzScheduler sched,
            CancellationToken cancellationToken = default)
        {
            qs = sched;

            IJob       job;
            IJobDetail jobDetail = firedTriggerBundle.JobDetail;

            try
            {
                job = sched.JobFactory.NewJob(firedTriggerBundle, scheduler);
            }
            catch (SchedulerException se)
            {
                await sched.NotifySchedulerListenersError($"An error occurred instantiating job to be executed. job= '{jobDetail.Key}'", se, cancellationToken).ConfigureAwait(false);

                throw;
            }
            catch (Exception e)
            {
                SchedulerException se = new SchedulerException($"Problem instantiating type '{jobDetail.JobType.FullName}: {e.Message}'", e);
                await sched.NotifySchedulerListenersError($"An error occurred instantiating job to be executed. job= '{jobDetail.Key}, message={e.Message}'", se, cancellationToken).ConfigureAwait(false);

                throw se;
            }

            jec = new JobExecutionContextImpl(scheduler, firedTriggerBundle, job);
        }
Exemplo n.º 7
0
        public SchedulerSignalerImpl(QuartzScheduler sched, QuartzSchedulerThread schedThread)
        {
            this.sched       = sched;
            this.schedThread = schedThread;

            log.Info("Initialized Scheduler Signaller of type: " + GetType());
        }
Exemplo n.º 8
0
        protected override IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs)
        {
            var sch = base.Instantiate(rsrcs, qs);

            sch.JobFactory = _serviceProvider.GetService <IJobFactory>();
            return(sch);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes the job execution context with given scheduler and bundle.
        /// </summary>
        /// <param name="sched">The scheduler.</param>
        /// <param name="firedBundle">The bundle offired triggers.</param>
        public virtual void Initialize(QuartzScheduler sched, TriggerFiredBundle firedBundle)
        {
            qs = sched;

            IJob      job;
            JobDetail jobDetail = firedBundle.JobDetail;

            try
            {
                job = sched.JobFactory.NewJob(firedBundle);
            }
            catch (SchedulerException se)
            {
                sched.NotifySchedulerListenersError(string.Format(CultureInfo.InvariantCulture, "An error occured instantiating job to be executed. job= '{0}'", jobDetail.FullName), se);
                throw;
            }
            catch (Exception e)
            {
                SchedulerException se = new SchedulerException(string.Format(CultureInfo.InvariantCulture, "Problem instantiating type '{0}'", jobDetail.JobType.FullName), e);
                sched.NotifySchedulerListenersError(string.Format(CultureInfo.InvariantCulture, "An error occured instantiating job to be executed. job= '{0}'", jobDetail.FullName), se);
                throw se;
            }

            jec = new JobExecutionContext(scheduler, firedBundle, job);
        }
Exemplo n.º 10
0
        public JsonResult GetLogFiles()
        {
            QuartzScheduler context = new QuartzScheduler(quartzJobStoreSettings.QuartzConnectionString);

            var list = QuartzProgram <AdminController> .GetJobHistory().Select(s => s.LOGFILE).Distinct().ToArray();

            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 11
0
        protected override IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs)
        {
            SetFactory(qs);
            var res = new CustomScheduler(qs, _container);

            AddListeners(res);
            return(res);
        }
Exemplo n.º 12
0
 private static void AddNewTriggersToScheduler(IList newItems)
 {
     foreach (TriggerModel item in newItems)
     {
         var trigger = QuartzTrigger.CreateTriggerForExistedJob(item.DateStart, item.RepeatType, item.TriggerId.ToString());
         QuartzScheduler.AttachTrigger(trigger);
     }
 }
Exemplo n.º 13
0
 private static void RemoveOldTriggersFromScheduler(IList oldItems)
 {
     foreach (TriggerModel item in oldItems)
     {
         var triggerKey = QuartzTrigger.GetTriggerKey(item.DateStart, item.RepeatType);
         QuartzScheduler.DetachTrigger(triggerKey);
     }
 }
Exemplo n.º 14
0
 public IActionResult ForceJob(JobTypeEnum?jobType)
 {
     if (jobType == null)
     {
         throw new Exception($"JobType '{ControllerContext.RouteData.Values[nameof(jobType)]}' is not defined.");
     }
     QuartzScheduler.ForceJobExecution(jobType.Value);
     return(Ok("Task started ..."));
 }
Exemplo n.º 15
0
 public IActionResult RestartJob(JobTypeEnum?jobType)
 {
     if (jobType == null)
     {
         throw new Exception($"JobType '{ControllerContext.RouteData.Values[nameof(jobType)]}' is not defined.");
     }
     QuartzScheduler.RestartJob(jobType.Value);
     return(Ok($"Task '{jobType}' has been restarted."));
 }
Exemplo n.º 16
0
        public void CreateQuartzSchedulerDatabase(string ConnectionStr)
        {
            if (ConnectionStr == string.Empty)
            {
                ConnectionStr = "data source=localhost;initial catalog=Quartz;integrated security=True";
            }
            QuartzScheduler context = new QuartzScheduler(ConnectionStr);

            context.CreateDatabase();
        }
Exemplo n.º 17
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (sched != null)
         {
             sched.Dispose();
             sched = null;
         }
     }
 }
Exemplo n.º 18
0
        public string HandleScheduler(string type)
        {
            string msg = "";

            try
            {
                if (type == "Run")
                {
                    if (sched != null)
                    {
                        if (!sched.IsShutdown)
                        {
                            sched.Clear();
                        }
                    }
                    QuartzScheduler.Run();
                }
                if (type == "Pause")
                {
                    if (sched != null)
                    {
                        if (!sched.IsShutdown)
                        {
                            sched.PauseAll();
                        }
                    }
                }
                if (type == "Resume")
                {
                    if (sched != null)
                    {
                        if (!sched.IsShutdown)
                        {
                            sched.ResumeAll();
                        }
                    }
                }
                if (type == "Shutdown")
                {
                    if (sched != null)
                    {
                        if (!sched.IsShutdown)
                        {
                            sched.Shutdown(false);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return(msg);
        }
 protected override async Task SchedulePostBootJobs()
 {
     if (!Configuration.LoadedConfiguration.FirstRunCompleted)
     {
         await QuartzScheduler.ScheduleJob <BcatFirstRunJob>("Normal");
     }
     else if (Configuration.LoadedConfiguration.IsProduction)
     {
         await QuartzScheduler.ScheduleJob <BcatCheckerJob>("Normal", Configuration.LoadedConfiguration.JobSchedules["Bcat"]);
     }
 }
Exemplo n.º 20
0
        public async Task Shutdown(bool shouldRestart = true)
        {
            if (!shouldRestart && RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                // Write out the automatic restart disabling file
                File.WriteAllText(Program.LOCAL_AUTOMATIC_RESTART_DISABLE_FLAG, "no restart");
            }

            await Context.Channel.SendMessageAsync("**[Admin]** OK, scheduling immediate shutdown");

            await QuartzScheduler.ScheduleJob <ShutdownJob>("Immediate");
        }
Exemplo n.º 21
0
 protected override IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler scheduler)
 {
     try
     {
         scheduler.JobFactory = _unityJobFactory;
         return(base.Instantiate(rsrcs, scheduler));
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Exemplo n.º 22
0
        private async Task Run(bool fastShutdown)
        {
            Console.WriteLine($"{(fastShutdown ? "Fast" : "Slow")} shutdown started");

            if (!fastShutdown)
            {
                // Shutdown the Scheduler
                await QuartzScheduler.Dispose();

                // Shutdown the DiscordBot
                await DiscordBot.Dispose();
            }
            else
            {
                // Create a backup of the current config.json just in case
                File.Copy(Boot.LOCAL_CONFIGURATION, Boot.LOCAL_CONFIGURATION_AUTOMATIC_BACKUP, true);
            }

            // Shutdown Twitter
            TwitterManager.Dispose();

            // Shutdown DigitalOcean
            DoApi.Dispose();

            // Shutdown S3
            S3Api.Dispose();

            // Shutdown BCAT
            BcatApi.Dispose();

            // Shutdown DAuth
            DAuthApi.Dispose();

            // Shutdown the HandlerMapper
            HandlerMapper.Dispose();

            // Shutdown the KeysetManager
            KeysetManager.Dispose();

            // Shutdown anything app-specific
            ShutdownAppSpecificItems();

            // Save the configuration
            Configuration.LoadedConfiguration.Write();

            if (!fastShutdown)
            {
                // Wait a little while
                await Task.Delay(1000 *ShutdownWaitTime);
            }

            Console.WriteLine("Shutdown complete");
        }
Exemplo n.º 23
0
        /// <summary>
        /// Construct a new <see cref="QuartzSchedulerThread" /> for the given
        /// <see cref="QuartzScheduler" /> as a non-daemon <see cref="Thread" />
        /// with normal priority.
        /// </summary>
        internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs)
        {
            Log = LogProvider.GetLogger(GetType());
            //ThreadGroup generatedAux = qs.SchedulerThreadGroup;
            this.qs      = qs;
            this.qsRsrcs = qsRsrcs;

            // start the underlying thread, but put this object into the 'paused'
            // state
            // so processing doesn't start yet...
            paused = true;
            halted = false;
        }
Exemplo n.º 24
0
 public ScheduledJobController(QuartzScheduler quartzScheduler,
                               ILocalizationService localizationService,
                               IPermissionService permissionService,
                               HttpContextBase httpContext,
                               IWorkContext workContext,
                               IDbContext dbContext)
 {
     this._quartzScheduler     = quartzScheduler;
     this._localizationService = localizationService;
     this._permissionService   = permissionService;
     this._httpContext         = httpContext;
     this._workContext         = workContext;
     this._dbContext           = dbContext;
 }
Exemplo n.º 25
0
        /// <summary>
        /// Construct a new <see cref="QuartzSchedulerThread" /> for the given
        /// <see cref="QuartzScheduler" /> as a <see cref="Thread" /> with the given
        /// attributes.
        /// </summary>
        internal QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs,
                                       bool setDaemon, int threadPrio) : base(qsRsrcs.ThreadName)
        {
            //ThreadGroup generatedAux = qs.SchedulerThreadGroup;
            this.qs      = qs;
            this.qsRsrcs = qsRsrcs;
            IsBackground = setDaemon;
            Priority     = (ThreadPriority)threadPrio;

            // start the underlying thread, but put this object into the 'paused'
            // state
            // so processing doesn't start yet...
            paused = true;
            halted = false;
        }
 private void RestartJob()
 {
     try
     {
         IScheduler sched = QuartzBase.GetRemoteScheduler();
         if (!sched.IsShutdown)
         {
             sched.Clear();
         }
         QuartzScheduler.Run();
     }
     catch (Exception)
     {
     }
 }
Exemplo n.º 27
0
        private static IScheduler CreateScheduler(string customerCode)
        {
            var ramJobStore = new RAMJobStore();

            var schedulerResources = new QuartzSchedulerResources
            {
                JobRunShellFactory = new StdJobRunShellFactory(),
                JobStore           = ramJobStore,
                Name = $"TasksScheduler_{customerCode}"
            };

            var threadPool = new DefaultThreadPool();

            threadPool.Initialize();

            schedulerResources.ThreadPool = threadPool;

            var quartzScheduler = new QuartzScheduler(schedulerResources, TimeSpan.Zero);

            ITypeLoadHelper loadHelper;

            try
            {
                loadHelper = ObjectUtils.InstantiateType <ITypeLoadHelper>(typeof(SimpleTypeLoadHelper));
            }
            catch (Exception e)
            {
                throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e);
            }

            loadHelper.Initialize();

            ramJobStore.Initialize(loadHelper, quartzScheduler.SchedulerSignaler);

            var standartScheduler = new StdScheduler(quartzScheduler);

            schedulerResources.JobRunShellFactory.Initialize(standartScheduler);

            quartzScheduler.Initialize();

            SchedulerRepository schedRep = SchedulerRepository.Instance;

            schedRep.Bind(standartScheduler);

            return(standartScheduler);
        }
        protected override async Task SchedulePostBootJobs()
        {
            // Check if this is the production bot
            if (Configuration.LoadedConfiguration.IsProduction)
            {
                // Schedule regular BCAT checks
                await QuartzScheduler.ScheduleJob <BcatCheckerJob>("Regular", Configuration.LoadedConfiguration.JobSchedules["Bcat"]);

                await DiscordBot.LoggingChannel.SendMessageAsync($"**[BootHousekeepingJob]** Scheduling immediate BCAT check");

                // Schedule a BCAT check now
                await QuartzScheduler.ScheduleJob <BcatCheckerJob>("Immediate");
            }

            // Schedule the recurring housekeeping job
            await QuartzScheduler.ScheduleJob <SsbuBotRecurringHousekeepingJob>("Regular", Configuration.LoadedConfiguration.JobSchedules["Housekeeping"]);
        }
Exemplo n.º 29
0
 private void ShutdownFromInstantiateException(IThreadPool tp, QuartzScheduler qs, bool tpInited, bool qsInited)
 {
     try
     {
         if (qsInited)
         {
             qs.Shutdown(false);
         }
         else if (tpInited)
         {
             tp.Shutdown(false);
         }
     }
     catch (Exception e)
     {
         Log.Error("Got another exception while shutting down after instantiation exception", e);
     }
 }
 public ImportProfileController(ILocalizationService localizationService,
                                IRepository <ImportProfile> importProfileRepository,
                                IImportProfileService importProfileService,
                                QuartzScheduler quartzScheduler,
                                IPermissionService permissionService,
                                HttpContextBase httpContext,
                                IWorkContext workContext,
                                IDbContext dbContext)
 {
     this._localizationService     = localizationService;
     this._quartzScheduler         = quartzScheduler;
     this._importProfileRepository = importProfileRepository;
     this._importProfileService    = importProfileService;
     this._permissionService       = permissionService;
     this._httpContext             = httpContext;
     this._workContext             = workContext;
     this._dbContext = dbContext;
 }
 /// <summary>
 ///     Instantiates the scheduler.
 /// </summary>
 /// <param name="rsrcs">The resources.</param>
 /// <param name="qs">The scheduler.</param>
 /// <returns>Scheduler.</returns>
 protected override IScheduler Instantiate(QuartzSchedulerResources rsrcs, QuartzScheduler qs)
 {
     var scheduler = base.Instantiate(rsrcs, qs);
     scheduler.JobFactory = _jobFactory;
     return scheduler;
 }