示例#1
0
        public void Configuration(IAppBuilder app)
        {
            //string constr = ConfigurationManager.ConnectionStrings["FriendFitDBContext"].ConnectionString;
            //GlobalConfiguration.Configuration.UseSqlServerStorage("MyHangFire");
            //app.UseHangfireDashboard();
            //app.UseHangfireServer();
            //ConfigureAuth(app);
            ConfigureAuth(app);
            string constr = ConfigurationManager.ConnectionStrings["FriendFitDBContext"].ConnectionString;

            GlobalConfiguration.Configuration.UseSqlServerStorage("MyHangFire");
            app.UseHangfireDashboard("/jobs");

            string Minutes = Cron.Minutely();
            SendWorkoutSMSController job = new SendWorkoutSMSController();

            RecurringJob.AddOrUpdate(() => job.SendSMSBeforeWorkoutToUser(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendSMSBeforeWorkoutToFriends(Minutes), Minutes);
            RecurringJob.AddOrUpdate(() => job.SendSMSToUserWhenWorkoutMissed(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendSMSFriendsWhenWorkoutMissed(Minutes), Minutes);

            RecurringJob.AddOrUpdate(() => job.SendEmailBeforeWorkoutToUser(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendEmailBeforeWorkoutToFriends(Minutes), Minutes);
            RecurringJob.AddOrUpdate(() => job.SendEmailToUserWhenWorkoutMissed(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendEmailFriendsWhenWorkoutMissed(Minutes), Minutes);

            RecurringJob.AddOrUpdate(() => job.SendNotificationBeforeWorkoutToUser(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendNotificationBeforeWorkoutToFriends(Minutes), Minutes);
            RecurringJob.AddOrUpdate(() => job.SendNotificationToUserWhenWorkoutMissed(Minutes), Minutes);
            //RecurringJob.AddOrUpdate(() => job.SendNotificationFriendsWhenWorkoutMissed(Minutes), Minutes);
            app.UseHangfireServer();
        }
示例#2
0
        // 执行的时间表。关于 CRON 详细信息,见 https://en.wikipedia.org/wiki/Cron#CRON_expression
        private string ConvertToCronExpression(ScheduleCronOptions cronOptions)
        {
            switch (cronOptions.scheduleCron)
            {
            case ScheduleCron.Minutely:
                return(Cron.Minutely());

            case ScheduleCron.Hourly:
                return(Cron.Hourly(cronOptions.Minute));

            case ScheduleCron.Daily:
                return(Cron.Daily(cronOptions.Hour, cronOptions.Minute));

            case ScheduleCron.Weekly:
                return(Cron.Weekly((DayOfWeek)cronOptions.Week, cronOptions.Hour, cronOptions.Minute));

            case ScheduleCron.Monthly:
                return(Cron.Monthly(cronOptions.Day, cronOptions.Hour, cronOptions.Minute));

            case ScheduleCron.Yearly:
                return(Cron.Yearly(cronOptions.Month, cronOptions.Day, cronOptions.Hour, cronOptions.Minute));

            default:
                throw new InvalidOperationException("Can not convert the scheduleCronOptions to cron.");
            }
        }
示例#3
0
        public void RunForever()
        {
            using (WithOneMinuteClock())
            {
                var count = 0;
                var done  = new ManualResetEvent(false);
                var crond = CronDaemon.Start <int>(
                    i =>
                {
                    count++;
                    if (count >= 3)
                    {
                        done.Set();
                    }
                },
                    i => i
                    );

                using (crond)
                {
                    crond.Add(1, Cron.Minutely(), int.MaxValue);

                    Assert.IsTrue(done.WaitOne(TimeSpan.FromSeconds(5)));
                }
            }
        }
示例#4
0
        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.UTF8;
            Console.WriteLine("服务开始了!");
            string tmpConnection = "server=rds5n95035s53i40c6m5o.mysql.rds.aliyuncs.com;uid=qingwatianya;pwd=qingwatianya101674;database=hangfire;Allow User Variables=True";

            GlobalConfiguration.Configuration
            .UseColouredConsoleLogProvider()
            .UseStorage(new MySqlStorage(tmpConnection));

            //支持基于队列的任务处理:任务执行不是同步的,而是放到一个持久化队列中,以便马上把请求控制权返回给调用者。
            //   BackgroundJob.Enqueue(() => Console.WriteLine("Simple!"));
            //延迟任务执行:不是马上调用方法,而是设定一个未来时间点再来执行。
            //  BackgroundJob.Schedule(() => Console.WriteLine("Reliable!"), TimeSpan.FromSeconds(5));
            //循环任务执行:一行代码添加重复执行的任务,其内置了常见的时间循环模式,也可基于CRON表达式来设定复杂的模式。
            // RecurringJob.AddOrUpdate(() => Console.WriteLine("Transparent!"), Cron.Minutely);//注意最小单位是分钟

            using (var server = new BackgroundJobServer())
            {
                //    //BackgroundJob.Enqueue(() => Dosomething());
                //    var tmpJobID = BackgroundJob.Enqueue(() => Console.WriteLine("开始咯"));
                //    tmpJobID = BackgroundJob.ContinueWith(tmpJobID, () => Console.WriteLine(string.Format("the parent job(ID:{0}) completed,turn to the child job!", tmpJobID)));

                RecurringJob.AddOrUpdate <Program>((Program) => Dosomething3(), Cron.Minutely());
                //Console.WriteLine("Hangfire Server started. Press any key to exit...");
                Console.ReadKey();
            }
        }
示例#5
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule(new DataModule(app));

            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            var container = builder.Build();

            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            //Register With OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
            GlobalConfiguration.Configuration
            .UseSqlServerStorage("DefaultConnection");

            app.UseHangfireDashboard("/myJobDashbord", new DashboardOptions()
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });
            RecurringJob.AddOrUpdate(
                () => ProductsController.ClearImages(), Cron.Minutely()
                );
            app.UseHangfireServer();
        }
示例#6
0
 protected override void OnStart(string[] args)
 {
     _server = new BackgroundJobServer();
     BackgroundJob.Enqueue <Class1>(x => x.F**k("xxx"));
     RecurringJob.AddOrUpdate(() => JobManager.FFF(), Cron.Minutely());
     RecurringJob.AddOrUpdate(() => Class1.FuckStatic(), Cron.Minutely());
 }
示例#7
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseHangfireDashboard();
            RecurringJob.AddOrUpdate <MessageService>(x => x.Send(), Cron.Minutely());
            app.UseRouting();


            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapHangfireDashboard();
            });
        }
示例#8
0
        public async Task <string> Start()
        {
            var contailers = await _container.GetContainerListAsync(Client);

            var ids = contailers.Select(x => x.ID).ToArray();

            lock ("1")
            {
                foreach (var id in ids)
                {
                    // if (!StaticValue.SENTRY_THREAD.ContainsKey((SentryEnum.Log, id)))
                    //     StaticValue.SENTRY_THREAD.TryAdd(
                    //         (SentryEnum.Log, id),
                    //         _sentry.StartLogs(Client, id, (_, __, ___) =>
                    //         {

                    //         })
                    //     );
                    var job     = Hangfire.Common.Job.FromExpression <ISentry>(x => x.StartStats(id));
                    var manager = new RecurringJobManager(JobStorage.Current);
                    manager.AddOrUpdate($"stats_{id}", job, Cron.Minutely(), TimeZoneInfo.Local);
                }
                _log.LogWarning("Sentry started");
                return("Done");
            }
        }
示例#9
0
        /// <summary>
        /// 运行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            TaskServicesManager.GetOrAdd("Clear Upload Files", token =>
            {
                if (_env != null)
                {
                    var webSiteUrl = $"images{Path.DirectorySeparatorChar}uploader{Path.DirectorySeparatorChar}";
                    var filePath   = Path.Combine(_env.WebRootPath, webSiteUrl);
                    if (Directory.Exists(filePath))
                    {
                        Directory.EnumerateFiles(filePath).Take(10).ToList().ForEach(file =>
                        {
                            try
                            {
                                if (token.IsCancellationRequested)
                                {
                                    return;
                                }
                                File.Delete(file);
                            }
                            catch { }
                        });
                    }
                }
                return(Task.CompletedTask);
            }, TriggerBuilder.Build(Cron.Minutely(10)));

            return(Task.CompletedTask);
        }
示例#10
0
 public HomeController(IBotRepository bot)
 {
     this.bot = bot;
     RecurringJob.AddOrUpdate(
         () => bot.CheckMatch(),
         Cron.Minutely());
 }
示例#11
0
        public string GetCron()
        {
            switch (UploadIntervalOption)
            {
            case UploadIntervalOption.Instantly:
                return(Cron.Minutely());

            case UploadIntervalOption.InMinutes:
                return(Cron.MinuteInterval(IntervalValue));

            case UploadIntervalOption.InHours:
                return(Cron.HourInterval(IntervalValue));

            case UploadIntervalOption.InDays:
                if (!OnExactDayTime.HasValue)
                {
                    throw new ArgumentOutOfRangeException();
                }
                int minute = OnExactDayTime.Value.Minute;
                int hour   = OnExactDayTime.Value.Hour;
                return($"{minute} {hour} */{IntervalValue} * *");

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
示例#12
0
        /// <summary>
        /// 运行任務
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(() =>
        {
            TaskServicesManager.GetOrAdd("單次任務", token => Task.Delay(1000));
            TaskServicesManager.GetOrAdd("周期任務", token => Task.Delay(1000), TriggerBuilder.Default.WithInterval(10000).Build());
            TaskServicesManager.GetOrAdd("Cron 任務", token => Task.Delay(1000), TriggerBuilder.Build(Cron.Secondly(5)));
            TaskServicesManager.GetOrAdd("超時任務", token => Task.Delay(2000), TriggerBuilder.Default.WithTimeout(1000).WithInterval(1000).WithRepeatCount(2).Build());

            // 本機調試時此處會抛出異常,配置文件中預設开啟了任務持久化到物理文件,此處異常只有首次加載時會抛出
            // 此處異常是示例自定义任務内部未進行捕獲異常時任務仍然能继续运行,不會導致整個進程崩溃退出
            // 此處程式碼可注释掉
            //TaskServicesManager.GetOrAdd("故障任務", token => throw new Exception("故障任務"));
            TaskServicesManager.GetOrAdd("取消任務", token => Task.Delay(1000)).Triggers.First().Enabled = false;

            // 創建任務并禁用
            TaskServicesManager.GetOrAdd("禁用任務", token => Task.Delay(1000)).Status = SchedulerStatus.Disabled;

            // 真實任務负责批次写入資料執行腳本到日誌中
            TaskServicesManager.GetOrAdd <DBLogTask>("SQL日誌", TriggerBuilder.Build(Cron.Minutely()));

            // 真實人物负责周期性設置健康檢查结果开關為开啟
            TaskServicesManager.GetOrAdd("健康檢查", token => Task.FromResult(DictHelper.SaveSettings(new BootstrapDict[] {
                new BootstrapDict()
                {
                    Category = "網站設置",
                    Name     = "健康檢查",
                    Code     = "1",
                    Define   = 0
                }
            })), TriggerBuilder.Build(Cron.Minutely(10)));
        });
示例#13
0
        protected void Application_Start()
        {
            JsonSerializerSettings jsSettings = new JsonSerializerSettings();

            jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            AreaRegistration.RegisterAllAreas();

            // Initialize background worker components
            Hangfire.GlobalConfiguration.Configuration.UseMemoryStorage();
            RecurringJob.AddOrUpdate(() => Readiness.MinutelyTaskChecker(), Cron.Minutely());
            RecurringJob.AddOrUpdate(() => Readiness.TerminationCheck(), Cron.Minutely());
            server = new BackgroundJobServer();

            // Web API routes
            System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            if (initialized)
            {
                return;
            }

            Log.AppendBlankLine();
            Global.LoadInitializers();
            initialized = true;
        }
示例#14
0
        public void Minutely_ReturnsFormattedString()
        {
            string expected = "* * * * *";
            string actual   = Cron.Minutely();

            Assert.Equal(expected, actual);
        }
示例#15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHangfireServer();
            app.UseHangfireDashboard();
            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // 立即执行的单次任务
            BackgroundJob.Enqueue(() => Console.WriteLine("Fire-and-forget"));
            // 创建计划任务,5分钟后执行
            BackgroundJob.Schedule(() => Console.WriteLine("Delayed"), TimeSpan.FromMinutes(1));
            // 创建周期性任务,每隔1分钟执行一次
            RecurringJob.AddOrUpdate <IMessageService>(o => o.Test(), Cron.Minutely());
            // 创建周期性任务,每天21:10执行,
            RecurringJob.AddOrUpdate("JobB", () => Console.WriteLine(DateTimeOffset.Now), "10 21 * * *");
            // 创建周期性任务,每天21:10执行
            RecurringJob.AddOrUpdate("JobC", () => Test(), "10 21 * * *", TimeZoneInfo.Local);
        }
示例#16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc();

            app.UseHangfireServer(new Hangfire.BackgroundJobServerOptions()
            {
                Queues      = new[] { "DEFAULT" },
                WorkerCount = 1
            });
            app.UseHangfireDashboard();

            RecurringJob.AddOrUpdate <QueueCheckJob>(q => q.Run(), Cron.Minutely());
        }
示例#17
0
        public static string PrepareCronType(CronSelectorModel model)
        {
            switch (model.CronType)
            {
            case CronType.Daily:
                return(Cron.Daily(model.Hour, model.Minute));

            case CronType.Hourly:
                return(Cron.Hourly(model.Minute));

            case CronType.Minutely:
                return(Cron.Minutely());

            case CronType.Monthly:
                return(Cron.Monthly(model.Day, model.Hour, model.Minute));

            case CronType.Weekly:
                return(Cron.Weekly(DayOfWeek.Monday, model.Hour, model.Minute));

            case CronType.Yearly:
                return(Cron.Yearly(model.Month, model.Day, model.Hour, model.Minute));
            }

            return(string.Empty);
        }
示例#18
0
 public void Run()
 {
     foreach (var item in actions)
     {
         RecurringJob.AddOrUpdate("定时任务测试", item, Cron.Minutely());
     }
 }
        /// <summary>
        /// Get the cron expression from the recurring options
        /// </summary>
        /// <param name="recurringOptions"></param>
        /// <returns></returns>
        private string GetCronExpression(RecurringOption recurringOptions)
        {
            var cronExpression = string.Empty;

            recurringOptions.Day = recurringOptions.Day == 0 ? 1 : recurringOptions.Day;

            switch (recurringOptions.Recurrence)
            {
            case Recurrence.Daily:
                cronExpression = Cron.Daily(recurringOptions.Hour, recurringOptions.Minute);
                break;

            case Recurrence.Hourly:
                cronExpression = Cron.Hourly(recurringOptions.Minute);
                break;

            case Recurrence.Minutely:
                cronExpression = Cron.Minutely();
                break;

            case Recurrence.Monthly:
                cronExpression = Cron.Monthly(recurringOptions.Day, recurringOptions.Hour, recurringOptions.Minute);
                break;

            case Recurrence.Weekly:
                cronExpression = Cron.Weekly(recurringOptions.DayOfWeek, recurringOptions.Hour, recurringOptions.Minute);
                break;

            case Recurrence.Yearly:
                cronExpression = Cron.Yearly(recurringOptions.Month, recurringOptions.Day, recurringOptions.Hour, recurringOptions.Minute);
                break;
            }

            return(cronExpression);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHangfireServer();
            app.UseHangfireDashboard();
            RecurringJob.AddOrUpdate(() => HangfireTask(), Cron.Minutely());

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "HangfireTest v1"));
            }

            app.UseLogDashboard();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            testHangfireTask = new TestHangfireTask("外部传入名称");
            testHangfireTask.Open();
        }
示例#21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors("VueCorsPolicy");

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseHangfireDashboard("/hangfire", new DashboardOptions()
            {
                Authorization = new[] { new CustomAuthorizeFilter() }
            });

            app.UseHangfireDashboard();
            app.UseHangfireServer();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub <Covid19InfoHub>("/covid19InfoHub"); // Use Covid19InfoHub class
            });

            //local time
            RecurringJob.AddOrUpdate <ICronJob>(
                cj => cj.GetCovid19Info(),
                Cron.Minutely(),
                TimeZoneInfo.Local);
        }
示例#22
0
        public void GetDescription_CronMinutely_ReturnsMinutely()
        {
            string expected = "Every minute";
            string actual   = Cron.GetDescription(Cron.Minutely());

            Assert.Equal(expected, actual);
        }
        public RecurringJobManagerFacts()
        {
            _id             = "recurring-job-id";
            _job            = Job.FromExpression(() => Method());
            _backgroundJob  = new BackgroundJob("my-id", _job, _now);
            _cronExpression = Cron.Minutely();
            _storage        = new Mock <JobStorage>();
            _factory        = new Mock <IBackgroundJobFactory>();
            _stateMachine   = new Mock <IStateMachine>();
            _factory.SetupGet(x => x.StateMachine).Returns(_stateMachine.Object);
            _nowFactory = () => _now;

            _timeZoneResolver = new Mock <ITimeZoneResolver>();
            _timeZoneResolver.Setup(x => x.GetTimeZoneById(It.IsAny <string>())).Returns(TimeZoneInfo.Utc);

            _connection = new Mock <IStorageConnection>();
            _storage.Setup(x => x.GetConnection()).Returns(_connection.Object);

            _transaction = new Mock <IWriteOnlyTransaction>();
            _connection.Setup(x => x.CreateWriteTransaction()).Returns(_transaction.Object);

            _factory.Setup(x => x.Create(It.Is <CreateContext>(ctx =>
                                                               ctx.Storage == _storage.Object &&
                                                               ctx.Connection == _connection.Object &&
                                                               ctx.InitialState == null)))
            .Returns(_backgroundJob);
        }
示例#24
0
        static void Main(string[] args)
        {
            Console.WriteLine("服务开始...");

            //1、配置HangFire数据库连接:首次连接数据库会自动创建12张相关的表
            string conn = "server=shaocx;uid=sa;pwd=1111;database=MyDB";

            GlobalConfiguration.Configuration.UseStorage(new SqlServerStorage(conn));

            //2、创建任务,自动将任务信息存储到数据系统表
            BackgroundJob.Enqueue <Class1>(x => x.F**k("我是鬼"));                        //执行一次其他类的非静态方法
            RecurringJob.AddOrUpdate(() => Console.WriteLine("你好啊"), Cron.Minutely()); //每分钟执行一次控制台输出
            RecurringJob.AddOrUpdate(() => Class1.FuckStatic(), Cron.Hourly(2));       //每2小时执行一次 其他类的静态方法
            RecurringJob.AddOrUpdate(() => Program.DoSomething2(), Cron.Daily());      //每天执行一次 其他类的静态方法

            var client = new BackgroundJobClient();

            //3、开启HangFire作业服务
            using (var _service = new BackgroundJobServer())
            {
                //4、控制台等待用户输入命令结束程序,如果控制台程序结束,HangFire服务跟宿主一起停止
                while (true)
                {
                    string tmpCmd = Console.ReadLine();
                    if (tmpCmd.ToLower().Equals("exit"))
                    {
                        break;
                    }
                    else
                    {
                        Console.WriteLine("可输入exit结束程序!");
                    }
                }
            }
        }
示例#25
0
        /// <summary>
        /// 运行任务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override Task ExecuteAsync(CancellationToken stoppingToken) => Task.Run(() =>
        {
            TaskServicesManager.GetOrAdd("单次任务", token => Task.Delay(1000));
            TaskServicesManager.GetOrAdd("周期任务", token => Task.Delay(1000), TriggerBuilder.Default.WithInterval(10000).Build());
            TaskServicesManager.GetOrAdd("Cron 任务", token => Task.Delay(1000), TriggerBuilder.Build(Cron.Secondly(5)));
            TaskServicesManager.GetOrAdd("超时任务", token => Task.Delay(2000), TriggerBuilder.Default.WithTimeout(1000).WithInterval(1000).WithRepeatCount(2).Build());

            // 本机调试时此处会抛出异常,配置文件中默认开启了任务持久化到物理文件,此处异常只有首次加载时会抛出
            // 此处异常是示例自定义任务内部未进行捕获异常时任务仍然能继续运行,不会导致整个进程崩溃退出
            // 此处代码可注释掉
            //TaskServicesManager.GetOrAdd("故障任务", token => throw new Exception("故障任务"));
            TaskServicesManager.GetOrAdd("取消任务", token => Task.Delay(1000)).Triggers.First().Enabled = false;

            // 创建任务并禁用
            TaskServicesManager.GetOrAdd("禁用任务", token => Task.Delay(1000)).Status = SchedulerStatus.Disabled;

            // 真实任务负责批次写入数据执行脚本到日志中
            TaskServicesManager.GetOrAdd <DBLogTask>("SQL日志", TriggerBuilder.Build(Cron.Minutely()));

            // 真实人物负责周期性设置健康检查结果开关为开启
            TaskServicesManager.GetOrAdd("健康检查", token => Task.FromResult(DictHelper.SaveSettings(new BootstrapDict[] {
                new BootstrapDict()
                {
                    Category = "网站设置",
                    Name     = "健康检查",
                    Code     = "1",
                    Define   = 0
                }
            })), TriggerBuilder.Build(Cron.Minutely(10)));
        });
        /// <summary>
        /// Static method to start the recurring job.
        /// </summary>
        public static void StartRecurringJob()
        {
            var cronPeriod = Environment.GetEnvironmentVariable("MORPHIC_CHECK_STALE_USERS_CRON_PERIOD");

            if (string.IsNullOrWhiteSpace(cronPeriod))
            {
                cronPeriod = DefaultCronPeriod;
            }
            switch (cronPeriod.ToLower())
            {
            case "disabled":
                // don't run the job. Delete if exists.
                RecurringJob.RemoveIfExists(JobId);
                return;

            case "daily":
                cronPeriod = Cron.Daily();
                break;

            case "weekly":
                cronPeriod = Cron.Weekly(DayOfWeek.Sunday);
                break;

            case "monthly":
                cronPeriod = Cron.Monthly();
                break;

            case "minutely":
                // probably only useful for development and or some rare situations!
                cronPeriod = Cron.Minutely();
                break;
            }
            RecurringJob.AddOrUpdate <UserCleanupJob>(JobId,
                                                      userCleanup => userCleanup.DeleteStaleUsers(), cronPeriod);
        }
        public void MultipleServerRunsRecurrentJobs()
        {
            // ARRANGE
            const int serverCount = 20;
            const int workerCount = 20;

            var options = new BackgroundJobServerOptions[serverCount];
            var storage = ConnectionUtils.CreateStorage(new MongoStorageOptions());
            var servers = new BackgroundJobServer[serverCount];

            var jobManagers = new RecurringJobManager[serverCount];

            for (int i = 0; i < serverCount; i++)
            {
                options[i] = new BackgroundJobServerOptions {
                    Queues = new[] { $"queue_options_{i}" }, WorkerCount = workerCount
                };

                servers[i]     = new BackgroundJobServer(options[i], storage);
                jobManagers[i] = new RecurringJobManager(storage);
            }

            try
            {
                // ACT
                for (int i = 0; i < serverCount; i++)
                {
                    var i1         = i;
                    var jobManager = jobManagers[i1];

                    for (int j = 0; j < workerCount; j++)
                    {
                        var j1         = j;
                        var queueIndex = j1 % options[i1].Queues.Length;
                        var queueName  = options[i1].Queues[queueIndex];
                        var job        = Job.FromExpression(() => Console.WriteLine("Setting signal for queue {0}",
                                                                                    queueName));
                        var jobId = $"job:[{i},{j}]";

                        jobManager.AddOrUpdate(jobId, job, Cron.Minutely(), new RecurringJobOptions
                        {
                            QueueName = queueName
                        });
                        jobManager.Trigger(jobId);
                    }
                }

                // let hangfire run for 1 sec
                Task.Delay(1000).Wait();
            }
            finally
            {
                for (int i = 0; i < serverCount; i++)
                {
                    servers[i].SendStop();
                    servers[i].Dispose();
                }
            }
        }
示例#28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            env.ConfigureNLog(Path.Combine(env.WebRootPath, "nlog.config"));

            app.UseHangfireServer();
            app.UseHangfireDashboard();
            RecurringJob.AddOrUpdate(() => AutoGetJobs.Run(), Cron.Minutely());
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            //app.Map("/index", r =>
            //{
            //    r.Run(context =>
            //    {
            //        //任务每分钟执行一次
            //        RecurringJob.AddOrUpdate(() => Console.WriteLine($"ASP.NET Core LineZero"), Cron.Minutely());
            //        return context.Response.WriteAsync("ok");
            //    });
            //});
            //app.Map("/one", r =>
            //{
            //    r.Run(context =>
            //    {
            //        //任务执行一次
            //        BackgroundJob.Enqueue(() => Console.WriteLine($"ASP.NET Core One Start LineZero{DateTime.Now}"));
            //        return context.Response.WriteAsync("ok");
            //    });
            //});
            //app.Map("/await", r =>
            //{
            //    r.Run(context =>
            //    {
            //        //任务延时两分钟执行
            //        BackgroundJob.Schedule(() => Console.WriteLine($"ASP.NET Core await LineZero{DateTime.Now}"), TimeSpan.FromMinutes(2));
            //        return context.Response.WriteAsync("ok");
            //    });
            //});

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            GlobalConfig.WWWRootPath = env.WebRootPath;

            //RecurringJob.AddOrUpdate(() => Console.WriteLine("test!  " + DateTime.Now), Cron.Minutely());
        }
示例#29
0
        private static void UseBackgroundJobsExecution(IServiceProvider serviceProvider)
        {
            var jobScheduler = serviceProvider.GetService <IJobScheduler>();

            jobScheduler.ScheduleRecurringJob <ISouthPingJob>(Cron.Minutely());
            jobScheduler.ScheduleRecurringJob <IWestPingJob>(Cron.Minutely());
            jobScheduler.ScheduleRecurringJob <IEastPingJob>(Cron.Minutely());
        }
        public WeatherForecastController(ILogger <WeatherForecastController> logger)
        {
            _logger = logger;
            TestHangfireTask testHangfireTask = new TestHangfireTask();

            RecurringJob.AddOrUpdate(() => testHangfireTask.HangfireTask(), Cron.Minutely());
            BackgroundJob.Enqueue(() => testHangfireTask.HangfireTaskOneTime());
        }