• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IJobExecutionContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中IJobExecutionContext的典型用法代码示例。如果您正苦于以下问题:C# IJobExecutionContext类的具体用法?C# IJobExecutionContext怎么用?C# IJobExecutionContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



IJobExecutionContext类属于命名空间,在下文中一共展示了IJobExecutionContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Execute

        /// <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);
            }
        }
开发者ID:kbdavis07,项目名称:FinalProject,代码行数:34,代码来源:SendMailJob.cs


示例2: Execute

        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();
        }
开发者ID:chrisofspades,项目名称:PickemApp,代码行数:28,代码来源:Program.cs


示例3: Execute

 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"));
 }
开发者ID:nunomaia,项目名称:quartznet,代码行数:7,代码来源:SimpleJob2.cs


示例4: Execute

        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("[email protected]", 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("[email protected]", "fredthefish");

                    foreach (var schedule in queSchedule)
                    {
                        smtp.Send(new MailMessage("[email protected]",
                                                  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));
        }
开发者ID:SmgIgor,项目名称:SenchaDemo,代码行数:60,代码来源:EmailSenderJob.cs


示例5: Execute

        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);
                    }

                }
            }
        }
开发者ID:qbajas,项目名称:PhotoHistory,代码行数:30,代码来源:PhotoNotifyJob.cs


示例6: Execute

        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;
            }
        }
开发者ID:jiasw,项目名称:TaskManager,代码行数:33,代码来源:SendMessageJob.cs


示例7: Execute

 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();
 }
开发者ID:R3MUSDevPack,项目名称:ReconnectedServerStuff,代码行数:7,代码来源:CorpMemberUpdateJob.cs


示例8: DoJob

        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));
            }
        }
开发者ID:bwrobel,项目名称:Experts,代码行数:26,代码来源:ThreadsOccupationReleaseJob.cs


示例9: Execute

 public void Execute(IJobExecutionContext context)
 {
     using (DiscoDataContext database = new DiscoDataContext())
     {
         LogContext.ReInitalize(database);
     }
 }
开发者ID:garysharp,项目名称:Disco,代码行数:7,代码来源:LogReInitalizeJob.cs


示例10: Execute

		/// <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"));
		}
开发者ID:CharlieBP,项目名称:quartznet,代码行数:37,代码来源:BadJob1.cs


示例11: Execute

        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");
        }
开发者ID:CodeGrappler,项目名称:Dreamhost-Dynamic-DNS-Updater,代码行数:35,代码来源:UpdateJob.cs


示例12: Execute

 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");
 }
开发者ID:rjonker1,项目名称:lightstone-data-platform,代码行数:7,代码来源:RefreshCache.cs


示例13: Execute

        /// <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 );
        }
开发者ID:rowlek,项目名称:Rock-ChMS,代码行数:39,代码来源:RockCleanup.cs


示例14: execute

 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"));
 }
开发者ID:jorgevr,项目名称:ENEX,代码行数:25,代码来源:MeasuresJob.cs


示例15: Execute

        /// <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++;
        }
开发者ID:vaskosound,项目名称:FantasyLeagueStats,代码行数:32,代码来源:ColorJob.cs


示例16: Execute

        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);
        }
开发者ID:keily,项目名称:LightOne,代码行数:33,代码来源:YhdArchiveJob.cs


示例17: Execute

        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... ");
        }
开发者ID:dhina4792,项目名称:ICT2106-XinemaProject,代码行数:25,代码来源:DataScrapperJob.cs


示例18: JobWasExecuted

 public void JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException)
 {
     if ((int)context.JobDetail.JobDataMap.Get(CashBalanceInquiryJob.CashOnHand) > 100)
     {
         context.JobDetail.JobDataMap.Put(CashBalanceInquiryJob.CashOnHand, 1);
     }
 }
开发者ID:tyronegroves,项目名称:BottomShelf,代码行数:7,代码来源:BalanceExceedsMaximumListener.cs


示例19: JobWasExecuted

        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);
            }
        }
开发者ID:CharlieBP,项目名称:quartznet,代码行数:25,代码来源:Job1Listener.cs


示例20: Execute

        /// <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();
        }
开发者ID:leo90skk,项目名称:qdms,代码行数:41,代码来源:EconomicReleaseUpdateJob.cs



注:本文中的IJobExecutionContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IJoinable类代码示例发布时间:2022-05-24
下一篇:
C# IJobDetail类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap