public void Execute(IJobExecutionContext context)
        {
            var queues = (ConcurrentQueue<MagicBoxOrder>)context.JobDetail.JobDataMap["queue"];
            var mbox = (MagicBoxOrder)context.JobDetail.JobDataMap["orders"];

            queues.Enqueue(mbox);
        }
Exemple #2
0
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute( IJobExecutionContext context )
        {
            var globalAttributesCache = GlobalAttributesCache.Read();
            globalAttributesCache.SetValue( "JobPulse", RockDateTime.Now.ToString(), true );

            UpdateScheduledJobs( context );
        }
 public void Execute(IJobExecutionContext context)
 {
     _Log.InfoFormat("Calendar Names: {0}", string.Join(",", context.Scheduler.GetCalendarNames()));
     outputMetadata(context.Scheduler.GetMetaData());
     Thread.Sleep(5000);
     //TODO: dump more data here
 }
        /// <summary>
        /// Executes the job.
        /// </summary>
        /// <param name="context">The job execution context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap data = context.MergedJobDataMap;

            MailMessage message = BuildMessageFromParameters(data);

            try
            {
                string portString = GetOptionalParameter(data, PropertySmtpPort);
                int? port = null;
                if (!string.IsNullOrEmpty(portString))
                {
                    port = Int32.Parse(portString);
                }

                var info = new MailInfo
                {
                    MailMessage = message,
                    SmtpHost = GetRequiredParameter(data, PropertySmtpHost),
                    SmtpPort = port,
                    SmtpUserName = GetOptionalParameter(data, PropertyUsername),
                    SmtpPassword = GetOptionalParameter(data, PropertyPassword),
                };
                Send(info);
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(string.Format(CultureInfo.InvariantCulture, "Unable to send mail: {0}", GetMessageDescription(message)), ex, false);
            }
        }
Exemple #5
0
 public virtual void Execute(IJobExecutionContext context)
 {
     // This job simply prints out its job name and the
     // date and time that it is running
     JobKey jobKey = context.JobDetail.Key;
     log.InfoFormat("SimpleJob2 says: {0} executing at {1}", jobKey, System.DateTime.Now.ToString("r"));
 }
        public void Execute(IJobExecutionContext context)
        {
            logger.Debug("执行重始任务!!!!!!!!!!!!!!!");
            if (Service1.isStop >= 1)
            {
                try
                {
                    var currentAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    var root = System.IO.Path.GetDirectoryName(currentAssembly);
                    var cmdPath = System.IO.Path.Combine(root, "_reStartEPMCSService.cmd");
                    //执行批处理进行恢复
                    logger.DebugFormat("开始任务:{0}", cmdPath);

                    System.Diagnostics.Process.Start("cmd.exe", "/c \"" + cmdPath + "\"").WaitForExit();

                    logger.Debug("********************执行重始任务完成。!!!!!!!!!!!!!!!");
                }
                catch (Exception ex)
                {

                    logger.ErrorFormat("执行重始任务失败,{0}", ex.Message);

                }
            }
            else
            {
                logger.DebugFormat("***********************停止执行重始任务!!!!!!!!!!!!!!!,isStop: flag {0},restart:{1} ", Service1.isStop, Service1.restart); ;
             }

            //throw new NotImplementedException();
        }
Exemple #7
0
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Executing " + DateTime.Now.ToString());

            //this is bad. should not hardcode domain here.
            string domain = "rcpickem.apphb.com";
            #if DEBUG
            domain = "localhost:64848";
            #endif

            // Initialize the WebRequest.
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://" + domain + "/Home/Sync?x=http://www.nfl.com/liveupdate/scorestrip/ss.xml");

            // Return the response.
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

            // Code to use the WebResponse goes here.
            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                Console.WriteLine("Successfully synced at " + DateTime.Now.ToString());
            }
            else
            {
                Console.WriteLine("Failed at " + DateTime.Now.ToString());
            }
            // Close the response to free resources.
            myResponse.Close();
        }
Exemple #8
0
        public void Execute(IJobExecutionContext context)
        {
            key++;

            int? time;
            if(context.JobDetail.JobDataMap.Contains("time"))
            {
                time = context.JobDetail.JobDataMap.GetIntValue("time");
                time++;
                context.JobDetail.JobDataMap["time"] = time;
            }
            else
            {
                time = 1;
                context.JobDetail.JobDataMap["time"] = time;
            }

            Trace.WriteLine(string.Format("time:{0}",time));

            //Trace.WriteLine(string.Format("MainJob Execute {0}",DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            //var jobDetail = JobBuilder.Create<SubJob>().UsingJobData("key",key).Build();

            //var trigger = TriggerBuilder.Create()
            //           .WithCronSchedule("*/5 * * * * ?")//5s
            //           .WithPriority(1)
            //           .Build();

            //context.Scheduler.ScheduleJob(jobDetail,trigger);
        }
        public void Execute(IJobExecutionContext context)
        {
            System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString()+" Executing photo notification job");
            AlbumRepository repo = new AlbumRepository();
            List<AlbumModel> albums = repo.GetAll();

            string path = context.JobDetail.JobDataMap.GetString("path");
            foreach(AlbumModel album in albums)
            {
                if (album.User.NotifyPhoto && album.NotificationPeriod!=null)
                {
                    DateTime time = album.NextNotification ?? DateTime.Today;
                    time = time.Date; //Data, godziny niepotrzebne
                    if (time <= DateTime.Today)
                    //if (time <= DateTime.Now)
                    {
                        album.NextNotification = DateTime.Today.AddDays(album.NotificationPeriod ?? 1);
                        //album.NextNotification = time.AddMinutes(album.NotificationPeriod * unit ?? 1);
                        repo.Update(album);

                        string link = path + "/Album/AddPhoto?albumId="+album.Id;

                        string body = string.Format("Hello {0},</br>It's time to add new photo to your album <a href='{1}'>{2}</a>",
                            album.User.Login,link,album.Name);
                        Helpers.SendEmailContextFree(album.User.Email, "Photo notification", body);
                    }

                }
            }
        }
        public void Execute(IJobExecutionContext context)
        {
            this.logger.Debug("EmailNotificationJob executing.");

            IEnumerable<EmailMessageDto> emails = this.emailNotificationDataService.Peek(5);

            BlogConfigurationDto configuration = this.configurationDataService.GetConfiguration();

            foreach (EmailMessageDto email in emails)
            {
                try
                {
                    using (SmtpClient smtp = new SmtpClient(configuration.SmtpConfiguration.SmtpHost, configuration.SmtpConfiguration.Port))
                    {
                        smtp.EnableSsl = configuration.SmtpConfiguration.UseSSL;
                        smtp.Credentials = new NetworkCredential(configuration.SmtpConfiguration.Username, configuration.SmtpConfiguration.Password);

                        using (MailMessage msg = email.ToMailMessage())
                        {
                            smtp.Send(msg);
                            this.logger.DebugFormat("Email sent! - Subject: {0} - To {1}", email.Subject, email.MailTo);
                        }

                        this.emailNotificationDataService.Dequeue(email);
                    }
                }
                catch (Exception e)
                {
                    this.logger.Error("Error occurred during sending the message.", e);
                    this.emailNotificationDataService.Queue(email);
                }
            }

            this.logger.Debug("EmailNotificationJob executed.");
        }
Exemple #11
0
        public void Execute(IJobExecutionContext context)
        {
            Log.Info(string.Format("Start! - {0}", System.DateTime.Now.ToString("r")));

            var queDay = DateTime.Now.ToString("ddd").ToUpperInvariant();
            var queLastRun = context.PreviousFireTimeUtc;
            var queTimeEnd = context.FireTimeUtc;

            using (var ent = new Commuticate.Repository.Entities())
            {
                //var comm =
                //    ent.Commuters.FirstOrDefault(c => c.Email.Equals("*****@*****.**", StringComparison.OrdinalIgnoreCase));

                //var rGroup = new RouteGroup() {Commuter = comm, Description = "First Route Group"};
                //ent.AddToRouteGroups(rGroup);

                //var route = new Route() {Commuter = comm, Description = "First Route"};
                //ent.AddToRoutes(route);

                //var rGroupR = new RouteGroupRoute() {RouteGroup = rGroup, RouteId = route.Id};
                //ent.AddToRouteGroupRoutes(rGroupR);
                //ent.SaveChanges();

                //var rGroup = ent.RouteGroups.FirstOrDefault(g => g.Description == "First Route Group");
                //var que = new Repository.Que() {Description = "John", RouteGroup = rGroup};
                //var sch = new Repository.QueSchedule() {AtTime = DateTime.Now.TimeOfDay, NotifyEmail = true, OnDays = queDay, Que = que};

                //ent.AddToQues(que);
                //ent.AddToQueSchedules(sch);
                //ent.SaveChanges();

                var queSchedule =
                    (from q in ent.QueSchedules
                     where q.OnDays.Contains(queDay)
                     //&& (q.AtTime >= queLastRun.TimeOfDay && q.AtTime < queTimeEnd.TimeOfDay)
                     select q);

                using (var smtp = new SmtpClient("mail.tecknonerd.com"))
                {
                    smtp.Credentials = new NetworkCredential("*****@*****.**", "fredthefish");

                    foreach (var schedule in queSchedule)
                    {
                        smtp.Send(new MailMessage("*****@*****.**",
                                                  schedule.Que.RouteGroup.Commuter.Email,
                                                  "Commuticate Que",
                                                  "It worked: " + DateTime.Now));

                        schedule.LastRun = DateTime.Now;
                    }
                }

                ent.SaveChanges();
            }

            Log.Info(string.Format("End! - {0}", System.DateTime.Now.ToString("r")));

            //Console.CursorLeft = 0;
            Console.WriteLine(String.Format("Scheduled: {0} - Ran: {1} ", context.ScheduledFireTimeUtc, context.FireTimeUtc));
        }
Exemple #12
0
        public virtual void JobWasExecuted(IJobExecutionContext inContext, JobExecutionException inException)
        {
            log.Info("Job1Listener says: Job was executed.");

            // Simple job #2
            IJobDetail job2 = JobBuilder.Create<SimpleJob2>()
                .WithIdentity("job2")
                .Build();

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

            try
            {
                // schedule the job to run!
                inContext.Scheduler.ScheduleJob(job2, trigger);
            }
            catch (SchedulerException e)
            {
                log.Warn("Unable to schedule job2!");
                Console.Error.WriteLine(e.StackTrace);
            }
        }
 public void Execute(IJobExecutionContext context)
 {
     var name = MethodBase.GetCurrentMethod().DeclaringType.Name;
     var db = new r3mus_DBEntities();
     SyncCorpMembers(db.CRONJobs.Where(job => job.JobName == name).FirstOrDefault());
     db.SaveChanges();
 }
        public void Execute(IJobExecutionContext context)
        {
            //Data crawling codes here
            System.Diagnostics.Debug.WriteLine("Executing job...");
            Scrapper scrapper = new Scrapper();
            scrapper.scrapCinemaName("https://www.google.com/movies?near=singapore&rl=1&stok=ABAPP2tdNR_5cLRa-6emW2UtecEL44SX2A%3A1456036737594");
            List<Cinema> cinemaList = scrapper.getCinemaNames();
            int size = cinemaList.Count() - 1;
            //int size = 10;
            Cinema cinema = new Cinema();

            while (size >= 0) {
                System.Diagnostics.Debug.WriteLine("size: " + size);
                //cinema.CinemaName = "name";
                //cinema.CinemaAddress = "addr";
                //cinemaGateway.Insert(cinema);
                cinema.CinemaName = cinemaList[size].CinemaName;
                System.Diagnostics.Debug.WriteLine("Cinena Name: " + cinema.CinemaName);
                cinema.CinemaAddress = cinemaList[size].CinemaAddress;
                System.Diagnostics.Debug.WriteLine("Cinema Address: " + cinema.CinemaAddress);
                cinemaGateway.Insert(cinema);
                size--;
            }
            System.Diagnostics.Debug.WriteLine("Job ended... ");
        }
Exemple #15
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                DateTime start = DateTime.Now;
                TaskLog.SendMessageLogInfo.WriteLogE("\r\n\r\n\r\n\r\n------------------发送信息任务开始执行 " + start.ToString("yyyy-MM-dd HH:mm:ss") + " BEGIN-----------------------------\r\n\r\n");

                //取出所有当前待发送的消息
                List<Message> listWait = SQLHelper.ToList<Message>(strSQL2);
                bool isSucess = false;
                if (listWait == null || listWait.Count == 0)
                {
                    TaskLog.SendMessageLogInfo.WriteLogE("当前没有等待发送的消息!");
                }
                else
                {
                    foreach (var item in listWait)
                    {
                        isSucess = MessageHelper.SendMessage(item);
                        TaskLog.SendMessageLogInfo.WriteLogE(string.Format("接收人:{0},类型:{1},内容:“{2}”的消息发送{3}", item.Receiver, item.Type.ToString(), item.Content, isSucess ? "成功" : "失败"));
                    }
                }
                DateTime end = DateTime.Now;
                TaskLog.SendMessageLogInfo.WriteLogE("\r\n\r\n------------------发送信息任务完成:" + end.ToString("yyyy-MM-dd HH:mm:ss") + ",本次共耗时(分):" + (end - start).TotalMinutes + " END------------------------\r\n\r\n\r\n\r\n");
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                TaskLog.SendMessageLogError.WriteLogE("发送信息任务异常", ex);
                //1.立即重新执行任务 
                e2.RefireImmediately = true;
            }
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
        /// fires that is associated with the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            Console.Error.WriteLine("---{0} executing.[{1}]", context.JobDetail.Key, DateTime.Now.ToString("r"));

            JobDataMap map = context.JobDetail.JobDataMap;

            int executeCount = 0;
            if (map.ContainsKey(NumExecutions))
            {
                executeCount = map.GetInt(NumExecutions);
            }

            executeCount++;

            map.Put(NumExecutions, executeCount);

            int delay = 5;
            if (map.ContainsKey(ExecutionDelay))
            {
                delay = map.GetInt(ExecutionDelay);
            }

            try
            {
                Thread.Sleep(delay);
            }
            catch (ThreadInterruptedException)
            {
            }

            Console.Error.WriteLine("  -{0} complete ({1}).", context.JobDetail.Key, executeCount);
        }
        /// <summary>
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // This job simply prints out its job name and the
            // date and time that it is running
            JobKey jobKey = context.JobDetail.Key;

            // Grab and print passed parameters
            JobDataMap data = context.JobDetail.JobDataMap;
            string favoriteColor = data.GetString(FavoriteColor);
            int count = data.GetInt(ExecutionCount);
            log.InfoFormat(
                "ColorJob: {0} executing at {1}\n  favorite color is {2}\n  execution count (from job map) is {3}\n  execution count (from job member variable) is {4}",
                jobKey,
                DateTime.Now.ToString("r"),
                favoriteColor,
                count, counter);

            // increment the count and store it back into the
            // job map so that job state can be properly maintained
            count++;
            data.Put(ExecutionCount, count);

            // Increment the local member variable
            // This serves no real purpose since job state can not
            // be maintained via member variables!
            counter++;
        }
        /// <summary>
        /// Called by the Schedule when a <see cref="IJobDetail" />
        /// was about to be executed (an associated <see cref="ITrigger" />
        /// has occured), but a <see cref="ITriggerListener" /> vetoed it's
        /// execution.
        /// </summary>
        /// <param name="context"></param>
        /// <seealso cref="JobToBeExecuted(IJobExecutionContext)"/>
        public void JobExecutionVetoed(IJobExecutionContext context)
        {
            Logger.InfoFormat("JobExecutionVetoed: {0}, {1}", context.JobDetail.Key.Name, context.JobDetail.Key.Group);

            var auditLog = GetAuditLog("JobExecutionVetoed", context);
            _persistanceStore.InsertAuditLog(auditLog);
        }
Exemple #19
0
        private void execute(IJobExecutionContext context)
        {
            prepareContextData(context);
            refreshConfigSettings();
            // we have no  credentials to move files so keep paths in external file
            var processFilesList = getProcessedMeasuresFilesList();
            IList<String> filePaths = new List<String>();

            if (processFilesList != null || processFilesList.Count != 0)
            {
                filePaths = getNoProcessedFtpFiles(processFilesList);
            } else
            {
                filePaths = getAllFtpFiles();
            }

            if (filePaths == null || !filePaths.Any())
            {
                _logger.Warn("There are no files to process.");
                return;
            }

            _logger.InfoFormat("Found {0} files to process", filePaths.Count);
            processFiles(filePaths);
        }
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler"/> when a <see cref="T:Quartz.ITrigger"/>
        ///             fires that is associated with the <see cref="T:Quartz.IJob"/>.
        /// </summary>
        /// <remarks>
        /// The implementation may wish to set a  result object on the
        ///             JobExecutionContext before this method exits.  The result itself
        ///             is meaningless to Quartz, but may be informative to
        ///             <see cref="T:Quartz.IJobListener"/>s or
        ///             <see cref="T:Quartz.ITriggerListener"/>s that are watching the job's
        ///             execution.
        /// </remarks>
        /// <param name="context">The execution context.</param>
        public void Execute(IJobExecutionContext context)
        {
            _logger = LogManager.GetCurrentClassLogger();

            JobDataMap dataMap = context.JobDetail.JobDataMap;
            EconomicReleaseUpdateJobSettings settings;
            try
            {
                settings = JsonConvert.DeserializeObject<EconomicReleaseUpdateJobSettings>((string)dataMap["settings"]);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Failed to deserialize data update job settings");
                return;
            }

            _logger.Info($"Data Update job {settings.Name} triggered.");

            _broker.Error += _broker_Error;

            var startDate = DateTime.Now.AddBusinessDays(-settings.BusinessDaysBack);
            var endDate = DateTime.Now.AddBusinessDays(settings.BusinessDaysAhead);
            var req = new EconomicReleaseRequest(startDate, endDate, dataLocation: DataLocation.ExternalOnly, dataSource: settings.DataSource);
            var releases = _broker.RequestEconomicReleases(req).Result; //no async support in Quartz, and no need for it anyway, this runs on its own thread
            _logger.Trace($"Economic release update job downloaded {releases.Count} items");

            JobComplete();
        }
Exemple #21
0
        public void Execute(IJobExecutionContext context)
        {
            string id = context.FireInstanceId;
            string name = concreteType.FullName;
            log.Info(Resources.Debug.JobExecuting.FormatWith(name, id));

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            try
            {
                DoWork(context);
            }
            catch (Exception exception)
            {
                log.Error(Resources.Error.UnhandledException, exception); // log here too, because the wrapper clears the stack trace.
                throw new JobExecutionException(exception);
            }
            finally
            {
                stopwatch.Stop();
                string duration = stopwatch.Elapsed.ToShortDurationString();
                log.Info(Resources.Debug.JobExecuted.FormatWith(name, id, duration));

                Dispose();
            }
        }
Exemple #22
0
        public void Execute(IJobExecutionContext context) {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            Logger.Info("开始抓取一号店数据");

            var downloadedCategories = new YhdCategoryExtractor().Extract().Result;
            var needProcessCategories = _CategoryArchiveService.Archive(downloadedCategories).OrderBy(c => c.ProductsUpdateTime);
            
            var taskLock = new SemaphoreSlim(initialCount: 1);
            var tasks = needProcessCategories.Select(async (category, index) => {
                await taskLock.WaitAsync();
                try {
                    var result = await ProcessCategoryAsync(category);
                    //■◆▲●□◇△○
                    Logger.Info(string.Join(" ", new[]{
                            string.Format("{0}", index + 1),
                            string.Format("[{0}]{1}", category.Number, category.Name),
                            string.Format("□{0} △{1}", result.Total, result.Changed)
                        }));
                }
                catch (Exception e) {
                    Logger.ErrorFormat("处理分类{0}{1}失败", e, category.Name, category.Number);
                }
                finally {
                    taskLock.Release();
                }
            });

            Task.WaitAll(tasks.ToArray());

            Logger.InfoFormat("抓取一号店数据完成,用时{0:0.#}分", stopwatch.Elapsed.TotalMinutes);
        }
        public override void DoJob(IJobExecutionContext context)
        {
            var repository = RepositoryHelper.Repository;

            var threadsToRelease = repository.Thread.Find(query: q => q.ByExpertReleaseDateExpiration());
            foreach (var thread in threadsToRelease)
            {
                if (thread.State == ThreadState.Occupied)
                {
                    thread.Expert = null;
                    thread.State = ThreadState.Unoccupied;
                    thread.AdditionalExpertProvisionValue = 0;

                    if (thread.Expert != null)
                    {
                        thread.Expert = null;
                        repository.Thread.Update(thread);
                    }
                }
                thread.ExpertReleaseDate = null;

                repository.Thread.Update(thread);

                repository.Thread.DeletePost(thread.Posts.Single(p => p.Type == PostType.Analyzing));
            }
        }
Exemple #24
0
		/// <summary>
		/// Called by the <see cref="IScheduler" /> when a Trigger" />
		/// fires that is associated with the <see cref="IJob" />.
		/// </summary>
		public virtual void Execute(IJobExecutionContext context)
		{
			JobKey jobKey = context.JobDetail.Key;
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            int denominator = dataMap.GetInt("denominator");
            log.InfoFormat("{0} with denominator {1}", "---" + jobKey + " executing at " + DateTime.Now, denominator);


			// a contrived example of an exception that
			// will be generated by this job due to a 
            // divide by zero error (only on first run)
			try
			{
                int calculation = 4815 / denominator;
			}
			catch (Exception e)
			{
				log.Info("--- Error in job!");
				JobExecutionException e2 = new JobExecutionException(e);


                // fix denominator so the next time this job run
                // it won't fail again
                dataMap.Put("denominator", "1");

				// this job will refire immediately
				e2.RefireImmediately = true;
				throw e2;
			}
			
			log.InfoFormat("---{0} completed at {1}", jobKey, DateTime.Now.ToString("r"));
		}
        public void Execute(IJobExecutionContext context)
        {
            Log.Info("Starting UpdateJob...");

            var currentIp = GetCurrentIP(this.config);
            if (currentIp == null)
            {
                Log.Info("Cancelling UpdateJob...");
                return;
            }

            Log.Info("Retrieved current IP: {0}", currentIp);

            foreach (KeyValuePair<string, string> d in GetDNSRecords(this.config))
            {
                if (currentIp != d.Value)
                {
                    Log.Info("Existing record {0} did not match retrieved IP, updating!", d.Key);

                    RemoveDNSRecord(d.Key, d.Value);

                    Log.Info("Removed existing DNS record.");

                    AddDNSRecord(d.Key, currentIp);

                    Log.Info("Added new DNS record for {0}.", d.Key);
                }
                else
                {
                    Log.Info("DNS record matches, finshing.");
                }
            }

            Log.Info("Finished UpdateJob");
        }
Exemple #26
0
        /// <summary> 
        /// Job that updates the JobPulse setting with the current date/time.
        /// This will allow us to notify an admin if the jobs stop running.
        /// 
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // get the job map
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            // delete accounts that have not been confirmed in X hours
            int userExpireHours = Int32.Parse( dataMap.GetString( "HoursKeepUnconfirmedAccounts" ) );
            DateTime userAccountExpireDate = DateTime.Now.Add( new TimeSpan( userExpireHours * -1,0,0 ) );

            UserService userService = new UserService();

            foreach (var user in userService.Queryable().Where(u => u.IsConfirmed == false && u.CreationDate < userAccountExpireDate))
            {
                userService.Delete( user, null );
            }

            userService.Save( null, null );

            // purge exception log
            int exceptionExpireDays = Int32.Parse( dataMap.GetString( "DaysKeepExceptions" ) );
            DateTime exceptionExpireDate = DateTime.Now.Add( new TimeSpan( userExpireHours * -1, 0, 0 ) );

            ExceptionLogService exceptionLogService = new ExceptionLogService();

            foreach ( var exception in exceptionLogService.Queryable().Where( e => e.ExceptionDate < exceptionExpireDate ) )
            {
                exceptionLogService.Delete( exception, null );
            }

            exceptionLogService.Save( null, null );
        }
 public void Execute(IJobExecutionContext context)
 {
     _log.InfoFormat("Attempting to execute the refresh cache job");
     _clear.Handle();
     _refresh.Handle();
     _log.InfoFormat("Executed the refresh cache job");
 }
Exemple #28
0
 public void Execute(IJobExecutionContext context)
 {
     using (DiscoDataContext database = new DiscoDataContext())
     {
         LogContext.ReInitalize(database);
     }
 }
Exemple #29
0
 private void execute(IJobExecutionContext context)
 {
     //jvr breAKpoint
     prepareContextData(context);
     refreshConfigSettings();
     //var plant = getPlant();
     // jvr we process all files with .xls termination
     string directoryPathToWatch = _configProvider.GetDirectoryPathToWatch();
     if (!Directory.Exists(directoryPathToWatch))
     {
         string error = string.Format("Directory '{0}' not found", directoryPathToWatch);
         _logger.Fatal(error);
         return;
     }
     _logger.Info(string.Format("Directory '{0}' found", directoryPathToWatch));
     var files = Directory.GetFiles(directoryPathToWatch, _configProvider.GetFilenamePattern()).ToList();
     if (!files.Any())
     {
         _logger.Warn("There are no files to process.");
         return;
     }
     _logger.Info(String.Format("Checking current files"));
     processFiles(files);
     _logger.Info(String.Format("Done checking current files"));
 }
 public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
 {
     if ((int)context.JobDetail.JobDataMap.Get(CashBalanceInquiryJob.CashOnHand) > 100)
     {
         context.JobDetail.JobDataMap.Put(CashBalanceInquiryJob.CashOnHand, 1);
     }
 }
Exemple #31
0
 public void Execute(IJobExecutionContext context)
 {
     logger.Trace(@"Executing Job A - {0:mm\:ss\.fff}", DateTime.Now - start);
 }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
        /// has fired, and it's associated <see cref="T:Quartz.IJobDetail" />
        /// is about to be executed.
        /// <para>
        /// It is called before the
        /// <see cref="M:Quartz.ITriggerListener.VetoJobExecution(Quartz.ITrigger,Quartz.IJobExecutionContext,System.Threading.CancellationToken)" />
        /// method of this interface.
        /// </para>
        /// </summary>
        ///
        /// <param name="trigger">  The <see cref="T:Quartz.ITrigger" /> that has fired. </param>
        /// <param name="context">  The <see cref="T:Quartz.IJobExecutionContext" /> that will be passed
        ///                         to the
        ///                         <see cref="T:Quartz.IJob" />'s<see cref="M:Quartz.IJob.Execute(Quartz.IJobExecutionContext)" />
        ///                         method. </param>
        /// <param name="token">    The cancellation instruction. </param>
        ///
        /// <returns>   The asynchronous result. </returns>
        ///
        /// <seealso cref="M:Quartz.ITriggerListener.TriggerFired(ITrigger,IJobExecutionContext,CancellationToken)"/>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public Task TriggerFired(ITrigger trigger, IJobExecutionContext context, CancellationToken token)
        {
            Console.WriteLine("SAMPLE: Trigger {0} fired for job {1}", trigger.Key.Name, context.JobDetail.Key.Name);
            return(Task.CompletedTask);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler" /> after a <see cref="T:Quartz.IJobDetail" />
        /// has been executed, and be for the associated <see cref="T:Quartz.Spi.IOperableTrigger" />'s
        /// <see cref="M:Quartz.Spi.IOperableTrigger.Triggered(Quartz.ICalendar)" /> method has been
        /// called.
        /// </summary>
        ///
        /// <param name="context">      The context. </param>
        /// <param name="jobException"> Details of the exception. </param>
        /// <param name="token">        The token. </param>
        ///
        /// <returns>   The asynchronous result. </returns>
        ///
        /// <seealso cref="M:Quartz.IJobListener.JobWasExecuted(IJobExecutionContext,JobExecutionException,CancellationToken)"/>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken token)
        {
            Console.WriteLine("SAMPLE: Job was executed: " + context.JobDetail.Key.Name);
            return(Task.CompletedTask);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.IJobDetail" />
        /// was about to be executed (an associated <see cref="T:Quartz.ITrigger" />
        /// has occurred), but a <see cref="T:Quartz.ITriggerListener" /> vetoed it's execution.
        /// </summary>
        ///
        /// <param name="context">  The context. </param>
        /// <param name="token">    The token. </param>
        ///
        /// <returns>   The asynchronous result. </returns>
        ///
        /// <seealso cref="M:Quartz.IJobListener.JobExecutionVetoed(IJobExecutionContext,CancellationToken)"/>
        /// <seealso cref="M:Quartz.IJobListener.JobToBeExecuted(Quartz.IJobExecutionContext,System.Threading.CancellationToken)"/>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public Task JobExecutionVetoed(IJobExecutionContext context, CancellationToken token)
        {
            Console.WriteLine("SAMPLE: Job execution vetoed: " + context.JobDetail.Key.Name);
            return(Task.CompletedTask);
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
        /// fires that is associated with the <see cref="T:Quartz.IJob" />.
        /// </summary>
        ///
        /// <remarks>
        /// The implementation may wish to set a  result object on the JobExecutionContext before this
        /// method exits.  The result itself is meaningless to Quartz, but may be informative to
        /// <see cref="T:Quartz.IJobListener" />s or
        /// <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
        /// execution.
        /// </remarks>
        ///
        /// <param name="context">  The execution context. </param>
        ///
        /// <returns>   The asynchronous result. </returns>
        ///
        /// <seealso cref="M:Quartz.IJob.Execute(IJobExecutionContext)"/>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        public Task Execute(IJobExecutionContext context)
        {
            Console.WriteLine("The current time is: {0}", SystemClock.Instance.GetCurrentInstant().ToDateTimeUtc().ToLocalTime());
            return(Task.CompletedTask);
        }
Exemple #36
0
 public void Execute(IJobExecutionContext context)
 {
     AppiumSession.KeepSessionLive();
 }
        public Task Execute(IJobExecutionContext context)
        {
            try
            {
                log = (log4net.ILog)context.JobDetail.JobDataMap["log"];

                log.Info("JobCriaInstalador.Execute iniciado");

                string PastaDrivers, PastaINNO, AppName, TextoCabecalho, CaminhoIcone;

                //busca instaladores não iniciados
                using (var db = new GeradorInstaladoresContext())
                {
                    if (db.DefinicoesGerais.Count() == 0)
                    {
                        log.Error("Definicoes gerais não configuradas");
                        return(Task.CompletedTask);
                    }

                    var definicoes_gerais = (from d in db.DefinicoesGerais
                                             select d)
                                            .First();

                    PastaDrivers   = definicoes_gerais.PastaDrivers;
                    PastaINNO      = definicoes_gerais.PastaINNO;
                    AppName        = definicoes_gerais.AppName;
                    TextoCabecalho = definicoes_gerais.TextoCabecalho;
                    CaminhoIcone   = definicoes_gerais.Icone;

                    log.Info("PastaDrivers: " + PastaDrivers);
                    log.Info("PastaINNO: " + PastaINNO);
                    log.Info("AppName: " + AppName);

                    var instaladores = from i in db.Instaladores
                                       where i.Status == (int)StatusCompilacao.NaoIniciado
                                       select i;

                    log.Info("Instaladores novos: " + instaladores.Count().ToString());
                    foreach (var instalador in instaladores)
                    {
                        instalador.Status = (int)StatusCompilacao.Compilando;
                    }

                    db.SaveChanges();
                }

                Instalador[] instaladores_a_compilar;

                using (var db = new GeradorInstaladoresContext())
                {
                    //desabilita proxy pois os dados serão utilizados com a conexão fechada
                    db.Configuration.ProxyCreationEnabled = false;

                    instaladores_a_compilar =
                        db.Instaladores
                        .Include("Equipamentos")
                        .Include("Equipamentos.ModeloEquipamento")
                        .Where(p => p.Status == (int)StatusCompilacao.Compilando)
                        .ToArray();
                }

                //compila um por um
                log.Info("Instaladores a compilar: " + instaladores_a_compilar.Count().ToString());
                foreach (var instalador in instaladores_a_compilar)
                {
                    CriadorInstalador criador = new CriadorInstalador(instalador, PastaDrivers, PastaINNO, AppName, TextoCabecalho, CaminhoIcone);

                    criador.OnMensagemProgresso += Criador_OnMensagemProgresso;
                    criador.OnErro      += Criador_OnErro;
                    criador.OnConclusao += Criador_OnConclusao;

                    criador.CriaInstaladorINNO();
                }

                log.Info("JobCriaInstalador.Execute finalizado");
            }
            catch (Exception e)
            {
                //loga o erro, não é possível exibir nenhuma mensagem ao user, já que este job roda no background
                log.Error(e);
            }

            return(Task.CompletedTask);
        }
        /// <summary>
        /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
        /// fires that is associated with the <see cref="T:Quartz.IJob" />.
        /// </summary>
        /// <param name="context">The execution context.</param>
        /// <exception cref="JobExecutionException">false</exception>
        /// <remarks>
        /// The implementation may wish to set a  result object on the
        /// JobExecutionContext before this method exits.  The result itself
        /// is meaningless to Quartz, but may be informative to
        /// <see cref="T:Quartz.IJobListener" />s or
        /// <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
        /// execution.
        /// </remarks>
        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                log4net.Config.XmlConfigurator.Configure();
                _context = context;
                _settings.Initialize(context);

                if (_settings.IndefinitePause)
                {
                    await context.Scheduler.PauseJob(context.JobDetail.Key);

                    Log.InfoFormat(CultureInfo.InvariantCulture,
                                   string.Format(Resources.Job_0_was_paused_indefinitely, _context.JobDetail.Key));
                    return;
                }

                _retryPolicyForIo = Policy.Handle <IOException>().WaitAndRetry(
                    retryCount: _settings.RetryCount,
                    sleepDurationProvider: attempt => TimeSpan.FromSeconds(_settings.RetryDelay),
                    onRetry: (exception, calculatedWaitDuration) =>
                {
                    Log.WarnFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Retrying_IO_operation_Exception_1, _context.JobDetail.Key, exception.Message));
                });
                _retryPolicyForHttp = Policy.Handle <HttpRequestException>().WaitAndRetryAsync(
                    retryCount: _settings.RetryCount,
                    sleepDurationProvider: attempt => TimeSpan.FromSeconds(_settings.RetryDelay),
                    onRetry: (exception, calculatedWaitDuration) =>
                {
                    Log.WarnFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_Retrying_Http_operation_Exception_1, _context.JobDetail.Key, exception.Message));
                });
                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_starting, _context.JobDetail.Key));
                }

                await Process();

                if (Log.IsDebugEnabled)
                {
                    Log.DebugFormat(CultureInfo.InvariantCulture, string.Format(Resources.Job_0_ended, _context.JobDetail.Key));
                }
            }
            catch (Exception ex)
            {
                if (_settings.PauseJobOnException)
                {
                    await context.Scheduler.PauseJob(context.JobDetail.Key);

                    Log.WarnFormat(CultureInfo.InvariantCulture,
                                   string.Format(Resources.Job_0_was_paused_because_of_error, _context.JobDetail.Key));
                }
                if (Log.IsDebugEnabled)
                {
                    if (!string.IsNullOrEmpty(ex.Message))
                    {
                        Log.Error(ex.Message, ex);
                    }
                    else
                    {
                        Log.Error("Uknown exception", ex);
                    }

                    while (ex.InnerException != null)
                    {
                        if (!string.IsNullOrEmpty(ex.InnerException.Message))
                        {
                            Log.Error(ex.InnerException.Message, ex.InnerException);
                        }

                        ex = ex.InnerException;
                    }
                }
                if (context.Scheduler.SchedulerName != "Private")
                {
                    throw new JobExecutionException(string.Format(Resources.Execution_monitor_job_0_failed, _context.JobDetail.Key), ex, false);
                }

                if (!Log.IsDebugEnabled)
                {
                    Log.Error(string.Format(Resources.Job_0_thrown_an_error_1, _context.JobDetail.Key, ex.Message));
                }
            }
        }
Exemple #39
0
 /// <summary>
 /// http://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontriggers.html
 /// </summary>
 /// <param name="context"></param>
 public abstract Task Execute(IJobExecutionContext context);
Exemple #40
0
 public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = new CancellationToken())
 {
     throw new NotImplementedException();
 }
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                JobDataMap dataMap = context.MergedJobDataMap;

                eventName      = dataMap.GetString("eventName");
                eventStartTime = dataMap.GetDateTime("eventStartTime");
                eventEndTime   = dataMap.GetDateTime("eventEndTime");
                regStartTime   = dataMap.GetDateTime("regStartTime");
                regEndTime     = dataMap.GetDateTime("regEndTime");

                EmailMessage em = new EmailMessage();

                em.Subject  = eventName + " Local Retreat";
                em.Message  = "Dear Saints, \r\n\r\n" + "Local Retreat – " + string.Format("{0: ddd, d-MMM-yyyy.}", eventStartTime);
                em.Message += "\r\n\r\nA local retreat that coincides with " + eventName + " is being organized.";
                em.Message += "\r\n\r\nPlease register at SMCHA(S) website http://www.smchsg.com/";
                em.Message += "\r\nAll initiates are encouraged to register for local retreats through this website to reduce administration work.";

                em.Message += "\r\n\r\nClosing date for sign-up is " + string.Format("{0: ddd, d-MMM-yyyy.}", regEndTime) + "before 12:00 midnight, to facilitate preparations.";

                em.Message += "\r\n\r\nAll participants are to refer to the attached <<Local Retreats_Guidelines For Application + Rules & Regulations.pdf>>.";
                em.Message += "\r\nAll participants are reminded to bring their own eating utensils.";

                //em.Message += "\r\n\r\nPlease take note that there is still group meditation on Saturday evening as the local retreat ends at 3:00p.m. on Saturday afternoon.
                em.Message += "\r\n\r\nWe look forward to your participation.";

//Attachment: Local Retreats_Guildelines for Application + Rules & Regulations (RevB).pdf
                em.Message += "\r\n\r\n\r\n\r\n\r\nWishing you Master's Love & Blessings,\r\nSingapore Centre";


                em.From = "*****@*****.**";
                //em.To = "[email protected], [email protected]";
                em.To = "*****@*****.**";

                List <SMCHSGManager.Models.MemberInfo> mis = _entities.MemberInfos.Where(a => a.InitiateTypeID == 1).OrderBy(a => a.aspnet_Users.UserName).ToList();
                foreach (SMCHSGManager.Models.MemberInfo mi in mis)
                {
                    string         userName = mi.aspnet_Users.UserName;
                    MembershipUser user     = Membership.GetUser(userName);
                    if (!string.IsNullOrEmpty(user.Email) && user.Email.Trim() != "*****@*****.**")
                    {
                        if (string.IsNullOrEmpty(em.bcc))
                        {
                            em.bcc = user.Email;
                        }
                        else
                        {
                            string email = user.Email.Replace('/', ',');
                            em.bcc += ", " + user.Email;
                        }
                    }
                }
                //em.bcc = "*****@*****.**";
                em.AttachFilePath = "";

                EmailService es = new EmailService();
                es.SendMessage(em);

                Debug.WriteLine("Scheduler is a success :" + DateTime.Now.ToString());
            }
            catch (JobExecutionException)
            {
                Debug.WriteLine("Scheduler Job Exception");
            }
        }
 public Task Execute(IJobExecutionContext context)
 {
     _logger.LogInformation("Ejecutado");
     return(Task.CompletedTask);
 }
 public Task JobToBeExecuted(IJobExecutionContext context, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(Task.CompletedTask);
 }
 public Task Execute(IJobExecutionContext context)
 {
     return(Task.FromResult(true));
 }
Exemple #45
0
 public void Execute(IJobExecutionContext context)
 {
 }
 public Task Execute(IJobExecutionContext context)
 {
     Console.WriteLine($"InjectSampleJobSingle {_options.WriteText} ");
     return(Task.CompletedTask);
 }
Exemple #47
0
        public async Task Execute(IJobExecutionContext context)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            logger.LogInformation("Updating Jenkins jobs.");

            var jenkinsChannel = client.Guilds.SelectMany(g => g.Channels).FirstOrDefault(c => c.Name == "jenkins") as SocketTextChannel;

            if (jenkinsChannel == null)
            {
                logger.LogWarning("Cannot find Jenkins channel.");
            }

            bool lockTaken = await semaphoreSlim.WaitAsync(0);

            if (!lockTaken)
            {
                logger.LogInformation("Update job already in progress, aborting update.");
                return;
            }
            try
            {
                var state = await stateStore.FetchState();

                var jobs = await jenkinsRestClient.FetchCachedWorkflowJobs();

                var updatedJobTasks = jobs.Select(j => jenkinsRestClient.FetchFullObject(j, false)).ToArray();

                await Task.WhenAll(updatedJobTasks);

                var updatedJobs = updatedJobTasks.Select(t => t.Result).Cast <WorkflowJob>().ToArray();
                logger.LogInformation($"{updatedJobs.Length} jobs found:\n{string.Join(",\n", updatedJobs.Select(r => r.Url).ToArray())}");
                var buildLinks = updatedJobs.SelectMany(j => j.builds).ToArray();

                var runTasks = buildLinks.Select(bl => jenkinsRestClient.FetchFullObject(bl)).ToArray();
                await Task.WhenAll(runTasks);

                var runs = runTasks.Select(t => t.Result).Select(r => r as WorkflowRun).Where(r => r != null).ToArray();

                var newRuns = runs.Where(r => r.Timestamp + r.Duration > state.LastUpdateDateTime && r.Result != null)
                              .ToArray();

                logger.LogInformation($"{newRuns.Length} new runs found:\n{string.Join(",\n", newRuns.Select(r => r.url).ToArray())}");

                // getting timezones is not platform agnostic, so try both ways
                TimeZoneInfo timezoneInfo = TimeZoneInfo.Utc;
                var          zones        = TimeZoneInfo.GetSystemTimeZones();
                timezoneInfo = zones.FirstOrDefault(tz => tz.Id == "Europe/London") ??
                               zones.FirstOrDefault(tz => tz.Id == "GMT Standard Time") ??
                               TimeZoneInfo.Utc;

                logger.LogInformation($"Using timezone {timezoneInfo.Id}");
                foreach (var newRun in newRuns)
                {
                    string passEmoji = $"[{newRun.Result}]";
                    if (newRun.Result == "SUCCESS")
                    {
                        passEmoji = ":white_check_mark:";
                    }
                    else if (newRun.Result == "FAILURE")
                    {
                        passEmoji = ":octagonal_sign:";
                    }
                    else if (newRun.Result == "ABORTED")
                    {
                        passEmoji = ":no_pedestrians:";
                    }
                    else if (newRun.Result == "UNSTABLE")
                    {
                        passEmoji = ":warning:";
                    }

                    string durationStr = $"Job ran for {(newRun.Duration.Hours > 0 ? $"{newRun.Duration.Hours} hours, " : "")}" +
                                         $"{(newRun.Duration.Minutes > 0 ? $"{newRun.Duration.Minutes} minutes, " : "")}" +
                                         $"{(newRun.Duration.Seconds > 0 ? $"{newRun.Duration.Seconds} seconds." : "")}";

                    var    localisedDateTime = TimeZoneInfo.ConvertTime(newRun.Timestamp.UtcDateTime, TimeZoneInfo.Utc, timezoneInfo);
                    string timestampStr      = localisedDateTime.ToLongTimeString();
                    var    embed             = new EmbedBuilder
                    {
                        // Embed property can be set within object initializer
                        Title = newRun.fullDisplayName,
                        Url   = newRun.url
                    };
                    await jenkinsChannel?.SendMessageAsync($"{passEmoji} [{timestampStr}] {newRun.fullDisplayName}. {durationStr}", false, embed.Build());
                }
                state.LastUpdateDateTime = DateTimeOffset.Now;
                await stateStore.SaveState(state);
            }
            catch (TaskCanceledException ex)
            {
                logger.LogError(ex, "Task cancelled exception getting Jenkins job status.");
                var innerExMessage = PrintInnerExceptions(ex.InnerException);
                await jenkinsChannel?.SendMessageAsync($":loudspeaker: Task cancelled exception. Error getting Jenkins job status:\n{innerExMessage}");
            }
            catch (OperationCanceledException ex)
            {
                logger.LogError(ex, "Operation cancelled exception getting Jenkins job status.");
                var innerExMessage = PrintInnerExceptions(ex.InnerException);
                await jenkinsChannel?.SendMessageAsync($":loudspeaker: Operation cancelled exception. Error getting Jenkins job status:\n{innerExMessage}");
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error getting Jenkins job status.");
                await jenkinsChannel?.SendMessageAsync($":loudspeaker: Error getting Jenkins job status: {ex.GetType().Name} - {ex.Message}");
            }
            finally
            {
                stopwatch.Stop();
                if (lockTaken)
                {
                    semaphoreSlim.Release();
                }
                logger.LogInformation($"Updating Jenkins jobs complete ({stopwatch.Elapsed.TotalSeconds} seconds).");
            }
        }
Exemple #48
0
 public void Execute(IJobExecutionContext context)
 {
     throw new NotImplementedException();
 }
Exemple #49
0
        public async Task Execute(IJobExecutionContext context)
        {
            _sid = long.Parse(context.JobDetail.Key.Name);
            using (var _quartzDao = new QuartzDao())
            {
                var getLocked = true;
                if (getLocked)
                {
                    IJobDetail job = context.JobDetail;
                    _logger.LogInformation($"节点[{node}] 准备执行任务[{job.JobDataMap["name"]}({_sid})]....");
                    try
                    {
                        if (job.JobDataMap["instance"] is TaskBase instance)
                        {
                            long traceId = await _quartzDao.GreateRunTrace(_sid, node);

                            Stopwatch   stopwatch = new Stopwatch();
                            TaskContext tctx      = new TaskContext(instance)
                            {
                                NodeName   = node,
                                Title      = $"{job.JobDataMap["name"]}",
                                TaskId     = _sid,
                                TraceId    = traceId,
                                ParamsDict = job.JobDataMap["params"] as Dictionary <string, object>
                            };
                            if (context.MergedJobDataMap["PreviousResult"] is object prev)
                            {
                                tctx.PreviousResult = prev;
                            }
                            try
                            {
                                stopwatch.Restart();
                                await instance.InnerRun(tctx);

                                stopwatch.Stop();
                                await _quartzDao.UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), Contract.Models.TaskRunResult.Success);

                                _logger.LogInformation($"任务[{job.JobDataMap["name"]}({_sid})]运行成功!{traceId} 用时{stopwatch.Elapsed.TotalMilliseconds.ToString()}ms");
                                //保存运行结果用于子任务触发
                                context.Result = tctx.Result;
                            }
                            catch (RunConflictException conflict)
                            {
                                stopwatch.Stop();
                                await _quartzDao.UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), Contract.Models.TaskRunResult.Conflict);

                                throw conflict;
                            }
                            catch (Exception e)
                            {
                                stopwatch.Stop();
                                await _quartzDao.UpdateRunTrace(traceId, Math.Round(stopwatch.Elapsed.TotalSeconds, 3), Contract.Models.TaskRunResult.Failed);

                                _logger.LogError(e, $"任务[{job.JobDataMap["name"]}({_sid})]运行失败!{traceId} ");
                                //这里抛出的异常会在JobListener的JobWasExecuted事件中接住
                                //如果吃掉异常会导致程序误以为本次任务执行成功
                                throw new BusinessRunException(e);
                            }
                        }
                    }
                    finally
                    {
                        //为了避免各节点之间的时间差,延迟1秒释放锁
                        System.Threading.Thread.Sleep(1000);
                    }
                }
                else
                {
                    //LogHelper.Info($"节点{node}抢锁失败!", _sid);
                    //throw new JobExecutionException("lock_failed");
                }
            }
            //return Task.FromResult(0);
        }
Exemple #50
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap             = context.JobDetail.JobDataMap;
            Guid?      groupGuid           = dataMap.GetString("EligibleFollowers").AsGuidOrNull();
            Guid?      systemEmailGuid     = dataMap.GetString("EmailTemplate").AsGuidOrNull();
            int        followingEventsSent = 0;

            if (groupGuid.HasValue && systemEmailGuid.HasValue)
            {
                var exceptionMsgs = new List <string>();

                using (var rockContext = new RockContext())
                {
                    var followingService                  = new FollowingService(rockContext);
                    var followingEventTypeService         = new FollowingEventTypeService(rockContext);
                    var followingEventNotificationService = new FollowingEventNotificationService(rockContext);

                    // Get all the active event types
                    var followingEvents = followingEventTypeService
                                          .Queryable().AsNoTracking()
                                          .Where(e =>
                                                 e.EntityTypeId.HasValue &&
                                                 e.IsActive)
                                          .OrderBy(e => e.Order)
                                          .ToList();

                    // Get the required event types
                    var requiredEventTypes = followingEvents
                                             .Where(e => e.IsNoticeRequired)
                                             .ToList();

                    // The people who are eligible to get following event notices based on the group type setting for this job
                    var eligiblePersonIds = new GroupMemberService(rockContext)
                                            .Queryable().AsNoTracking()
                                            .Where(m =>
                                                   m.Group != null &&
                                                   m.Group.Guid.Equals(groupGuid.Value) &&
                                                   m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                   m.Person != null &&
                                                   m.Person.Email != null &&
                                                   m.Person.Email != string.Empty &&
                                                   m.Person.EmailPreference != EmailPreference.DoNotEmail &&
                                                   m.Person.IsEmailActive)
                                            .Select(m => m.PersonId)
                                            .Distinct()
                                            .ToList();

                    // Get all the subscriptions for the eligible people
                    var eventSubscriptions = new FollowingEventSubscriptionService(rockContext)
                                             .Queryable("PersonAlias").AsNoTracking()
                                             .Where(f => eligiblePersonIds.Contains(f.PersonAlias.PersonId))
                                             .ToList();

                    // Dictionaries used to store information that will be used to create notification.
                    // Key: personId, Value: list of event type ids that person subscribes to
                    var personSubscriptions = new Dictionary <int, List <int> >();

                    // Key: personId, Value: list of following ids that person follows
                    var personFollowings = new Dictionary <int, List <int> >();

                    // Key: following event type id Value: Dictionary of entity id and formatted event notice for the entity
                    var eventsThatHappened = new Dictionary <int, Dictionary <int, string> >();

                    // Get the subscriptions for each eligible person.
                    foreach (int personId in eligiblePersonIds)
                    {
                        var personEventTypes = eventSubscriptions
                                               .Where(s => s.PersonAlias.PersonId == personId)
                                               .Select(s => s.EventType)
                                               .ToList();
                        personEventTypes.AddRange(requiredEventTypes);
                        if (personEventTypes.Any())
                        {
                            personSubscriptions.AddOrIgnore(
                                personId,
                                personEventTypes.OrderBy(e => e.Order).ThenBy(e => e.Name).Select(e => e.Id).Distinct().ToList());
                        }
                    }

                    // Get a distinct list of each Entity Type / Entity that is being followed by anyone that subscribes to events.
                    var followings = followingService
                                     .Queryable("PersonAlias").AsNoTracking()
                                     .Where(f => personSubscriptions.Keys.Contains(f.PersonAlias.PersonId) &&
                                            string.IsNullOrEmpty(f.PurposeKey))
                                     .ToList();

                    // group the followings by their type
                    var followedEntityIds = new Dictionary <int, List <int> >();
                    foreach (var followedEntity in followings
                             .Select(f => new
                    {
                        f.EntityTypeId,
                        f.EntityId
                    })
                             .Distinct())
                    {
                        followedEntityIds.AddOrIgnore(followedEntity.EntityTypeId, new List <int>());
                        followedEntityIds[followedEntity.EntityTypeId].Add(followedEntity.EntityId);
                    }

                    // group the followings by the follower
                    foreach (int personId in personSubscriptions.Select(s => s.Key))
                    {
                        var personFollowing = followings
                                              .Where(f => f.PersonAlias.PersonId == personId)
                                              .Select(f => f.Id)
                                              .ToList();

                        personFollowings.Add(personId, personFollowing);
                    }

                    var timestamp = RockDateTime.Now;

                    // For each Entity Type paired with a list of followed entities.
                    foreach (var entityTypeWithFollowedList in followedEntityIds)
                    {
                        // Get the Entity Type
                        EntityTypeCache itemEntityType = EntityTypeCache.Get(entityTypeWithFollowedList.Key);
                        if (itemEntityType != null && itemEntityType.AssemblyName != null)
                        {
                            // get the actual type of what is being followed
                            Type entityType = itemEntityType.GetEntityType();
                            if (entityType != null)
                            {
                                var dbContext = Reflection.GetDbContextForEntityType(entityType);
                                if (dbContext != null)
                                {
                                    var serviceInstance = Reflection.GetServiceForEntityType(entityType, dbContext);
                                    if (serviceInstance != null)
                                    {
                                        MethodInfo qryMethod = serviceInstance.GetType().GetMethod("Queryable", new Type[] { });
                                        var        entityQry = qryMethod.Invoke(serviceInstance, new object[] { }) as IQueryable <IEntity>;

                                        // If looking at person alias following, make sure to exclude deceased people
                                        if (entityType == typeof(Rock.Model.PersonAlias))
                                        {
                                            var personAliasQry = entityQry as IQueryable <PersonAlias>;
                                            if (personAliasQry != null)
                                            {
                                                entityQry = personAliasQry.Where(p => !p.Person.IsDeceased);
                                            }
                                        }

                                        var entityList = entityQry.Where(q => entityTypeWithFollowedList.Value.Contains(q.Id)).ToList();

                                        // If there are any followed entities of this type
                                        if (entityList.Any())
                                        {
                                            // Get the active event types for this entity type
                                            foreach (var eventType in followingEvents.Where(e => e.FollowedEntityTypeId == entityTypeWithFollowedList.Key))
                                            {
                                                try
                                                {
                                                    // Get the component
                                                    var eventComponent = eventType.GetEventComponent();
                                                    if (eventComponent != null)
                                                    {
                                                        // Get the previous notifications for this event type
                                                        var previousNotifications = followingEventNotificationService
                                                                                    .Queryable()
                                                                                    .Where(n => n.FollowingEventTypeId == eventType.Id)
                                                                                    .ToList();

                                                        // check each entity that is followed (by anyone)
                                                        foreach (IEntity entity in entityList)
                                                        {
                                                            var previousNotification = previousNotifications
                                                                                       .Where(n => n.EntityId == entity.Id)
                                                                                       .FirstOrDefault();
                                                            DateTime?lastNotification = previousNotification != null ? previousNotification.LastNotified : ( DateTime? )null;

                                                            // If ok to send on this day
                                                            var today = RockDateTime.Today;
                                                            if (eventType.SendOnWeekends || (today.DayOfWeek != DayOfWeek.Saturday && today.DayOfWeek != DayOfWeek.Sunday))
                                                            {
                                                                // if the Event Component is one that implements the Additional Merge Fields interface, use that method.
                                                                if (eventComponent is IEventComponentAdditionalMergeFields eventComponentAdditionalMergeFields)
                                                                {
                                                                    var followedEventList = new Dictionary <string, List <object> >();
                                                                    if (eventComponentAdditionalMergeFields.HasEventHappened(eventType, entity, lastNotification, out followedEventList))
                                                                    {
                                                                        // Store the event type id and the entity for later processing of notifications
                                                                        eventsThatHappened.AddOrIgnore(eventType.Id, new Dictionary <int, string>());

                                                                        eventsThatHappened[eventType.Id].Add(
                                                                            entity.Id,
                                                                            eventComponentAdditionalMergeFields.FormatEntityNotification(eventType, entity, followedEventList));
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    if (eventComponent.HasEventHappened(eventType, entity, lastNotification))
                                                                    {
                                                                        // Store the event type id and the entity for later processing of notifications
                                                                        eventsThatHappened.AddOrIgnore(eventType.Id, new Dictionary <int, string>());

                                                                        eventsThatHappened[eventType.Id].Add(
                                                                            entity.Id,
                                                                            eventComponent.FormatEntityNotification(eventType, entity));
                                                                    }
                                                                }

                                                                if (previousNotification == null)
                                                                {
                                                                    previousNotification = new FollowingEventNotification();
                                                                    previousNotification.FollowingEventTypeId = eventType.Id;
                                                                    previousNotification.EntityId             = entity.Id;
                                                                    followingEventNotificationService.Add(previousNotification);
                                                                }

                                                                previousNotification.LastNotified = timestamp;
                                                            }
                                                        }

                                                        rockContext.SaveChanges();
                                                    }

                                                    eventType.LastCheckDateTime = RockDateTime.Now;
                                                }
                                                catch (Exception ex)
                                                {
                                                    exceptionMsgs.Add(string.Format("An exception occurred calculating events for the '{0}' following type:{1}    {2}", eventType.Name, Environment.NewLine, ex.Messages().AsDelimited(Environment.NewLine + "   ")));
                                                    ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // send notifications
                    var possibleRecipients = new PersonService(rockContext)
                                             .Queryable().AsNoTracking()
                                             .Where(p => personSubscriptions.Keys.Contains(p.Id))
                                             .ToList();

                    // Loop through the possible recipients that actually subscribe to events
                    foreach (var personSubscription in personSubscriptions)
                    {
                        // Get the recipient person
                        int personId = personSubscription.Key;
                        var person   = possibleRecipients.Where(p => p.Id == personId).FirstOrDefault();
                        if (person != null)
                        {
                            try
                            {
                                // Make sure person is actually following anything
                                if (personFollowings.ContainsKey(personId))
                                {
                                    // Dictionary to store the entities that had an event for each event type
                                    var personEventTypeNotices = new List <FollowingEventTypeNotices>();

                                    // Get the event types that person subscribes to
                                    foreach (var eventType in eventsThatHappened.Where(e => personSubscription.Value.Contains(e.Key)))
                                    {
                                        // Check the permissions of the person for the following event subscription.
                                        var followingEventType = followingEvents.Where(e => e.Id == eventType.Key).FirstOrDefault();
                                        if (followingEventType.IsAuthorized(Authorization.VIEW, person))
                                        {
                                            // Get the EntityTypeId for this event type
                                            int entityTypeId = followingEventType.FollowedEntityTypeId.Value;

                                            // Find all the entities with this event type that the person follows
                                            var personFollowedEntityIds = followings
                                                                          .Where(f =>
                                                                                 personFollowings[personId].Contains(f.Id) &&
                                                                                 f.EntityTypeId == entityTypeId)
                                                                          .Select(f => f.EntityId)
                                                                          .ToList();

                                            // Get any of those entities that had an event happen
                                            var personFollowedEntities = eventType.Value
                                                                         .Where(e => personFollowedEntityIds.Contains(e.Key))
                                                                         .ToList();

                                            // If any were found
                                            if (personFollowedEntities.Any())
                                            {
                                                // Add the entry
                                                var eventTypeObj = followingEvents.Where(e => e.Id == eventType.Key).FirstOrDefault();
                                                if (eventTypeObj != null)
                                                {
                                                    personEventTypeNotices.Add(new FollowingEventTypeNotices(eventTypeObj, personFollowedEntities.Select(e => e.Value).ToList()));
                                                }
                                            }
                                        }
                                    }

                                    // If there are any events for any of the entities that this person follows, send a notification
                                    if (personEventTypeNotices.Any())
                                    {
                                        // Send the notice
                                        var mergeFields = new Dictionary <string, object>();
                                        mergeFields.Add("Person", person);
                                        mergeFields.Add("EventTypes", personEventTypeNotices.OrderBy(e => e.EventType.Order).ToList());

                                        var emailMessage = new RockEmailMessage(systemEmailGuid.Value);
                                        emailMessage.AddRecipient(new RockEmailMessageRecipient(person, mergeFields));
                                        var errors = new List <string>();
                                        emailMessage.Send(out errors);
                                        exceptionMsgs.AddRange(errors);
                                        if (!errors.Any())
                                        {
                                            followingEventsSent++;
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                exceptionMsgs.Add(string.Format("An exception occurred sending event notice to '{0}':{1}    {2}", person.FullName, Environment.NewLine, ex.Messages().AsDelimited(Environment.NewLine + "   ")));
                                ExceptionLogService.LogException(ex, System.Web.HttpContext.Current);
                            }
                        }
                    }
                }

                context.Result = string.Format("{0} following events emails sent", followingEventsSent);

                if (exceptionMsgs.Any())
                {
                    throw new Exception("One or more exceptions occurred calculating following events..." + Environment.NewLine + exceptionMsgs.AsDelimited(Environment.NewLine));
                }
            }
        }
        public void Execute(IJobExecutionContext context)
        {
            Config = CommonHelper.GetConfigFromDataMap(context.JobDetail.JobDataMap);

            Check();
        }
Exemple #52
0
 /// <summary>
 /// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
 /// fires that is associated with the <see cref="IJob" />.
 /// <p>
 /// The implementation may wish to set a  result object on the
 /// JobExecutionContext before this method exits.  The result itself
 /// is meaningless to Quartz, but may be informative to
 /// <see cref="IJobListener" />s or
 /// <see cref="ITriggerListener" />s that are watching the job's
 /// execution.
 /// </p>
 /// <param name="context">The execution context.</param>
 /// </summary>
 public void Execute(IJobExecutionContext context)
 {
     JobHasFired = true;
 }
Exemple #53
0
 public async Task Execute(IJobExecutionContext context)
 {
     await ExecuteJob(context, Run);
 }
Exemple #54
0
 public void Execute(IJobExecutionContext context)
 {
     var scheduler = (DailyEconomicScheduler)context.JobDetail.JobDataMap["scheduler"];
     var task      = scheduler.PrepareDailyReminder();
 }
Exemple #55
0
 /// <summary>
 /// Called by the <see cref="IScheduler" /> when a
 /// <see cref="ITrigger" /> fires that is associated with
 /// the <see cref="IJob" />.
 /// </summary>
 public virtual Task Execute(IJobExecutionContext context)
 {
     // Say Hello to the World and display the date/time
     Console.WriteLine($"Hello World! - {DateTime.Now:r}");
     return(Task.CompletedTask);
 }
 public override async Task Execute(IJobExecutionContext context)
 {
     await Job(DateTime.Now);
 }
Exemple #57
0
 public void Execute(IJobExecutionContext context)
 {
     ProcessExceptionInfo();
 }
Exemple #58
0
 /// <summary>
 /// Called by the <see cref="T:Quartz.IScheduler" /> when a <see cref="T:Quartz.ITrigger" />
 /// fires that is associated with the <see cref="T:Quartz.IJob" />.
 /// </summary>
 /// <param name="context">The execution context.</param>
 /// <returns>Task.</returns>
 /// <remarks>The implementation may wish to set a  result object on the
 /// JobExecutionContext before this method exits.  The result itself
 /// is meaningless to Quartz, but may be informative to
 /// <see cref="T:Quartz.IJobListener" />s or
 /// <see cref="T:Quartz.ITriggerListener" />s that are watching the job's
 /// execution.</remarks>
 public Task Execute(IJobExecutionContext context)
 {
     this.context = context;
     return(Task.Run(Execute));
 }
Exemple #59
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap           = context.JobDetail.JobDataMap;
            var        emailTemplateGuid = dataMap.Get("SystemEmail").ToString().AsGuid();
            var        groupGuid         = dataMap.Get("Group").ToString().AsGuid();
            var        sendToDescendants = dataMap.Get("SendToDescendantGroups").ToString().AsBoolean();

            var rockContext = new RockContext();
            var group       = new GroupService(rockContext).Get(groupGuid);

            if (group != null)
            {
                List <int> groupIds = new List <int>();
                GetGroupIds(groupIds, sendToDescendants, group);

                var recipients = new List <RockEmailMessageRecipient>();

                var groupMemberList = new GroupMemberService(rockContext).Queryable().Where(gm =>
                                                                                            groupIds.Contains(gm.GroupId) &&
                                                                                            gm.GroupMemberStatus == GroupMemberStatus.Active)
                                      .ToList();
                foreach (GroupMember groupMember in groupMemberList)
                {
                    var person = groupMember.Person;
                    if (!person.IsEmailActive || person.Email.IsNullOrWhiteSpace() || person.EmailPreference == EmailPreference.DoNotEmail)
                    {
                        continue;
                    }

                    var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                    mergeFields.Add("Person", person);
                    mergeFields.Add("GroupMember", groupMember);
                    mergeFields.Add("Group", groupMember.Group);

                    recipients.Add(new RockEmailMessageRecipient(groupMember.Person, mergeFields));
                }

                var errors = new List <string>();
                if (recipients.Any())
                {
                    var emailMessage = new RockEmailMessage(emailTemplateGuid);
                    emailMessage.SetRecipients(recipients);
                    emailMessage.Send(out errors);
                }

                context.Result = string.Format("{0} emails sent", recipients.Count());

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append(string.Format("{0} Errors: ", errors.Count()));
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    context.Result += errorMessage;
                    var         exception = new Exception(errorMessage);
                    HttpContext context2  = HttpContext.Current;
                    ExceptionLogService.LogException(exception, context2);
                    throw exception;
                }
            }
        }
Exemple #60
0
 public override async Task Execute(IJobExecutionContext context)
 {
     await Job();
 }