// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
                              IBackgroundJobClient backgroundJobClient,
                              IRecurringJobManager recurringJobManager,
                              IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "mDome API V1");
            });
            //app.UseHttpsRedirection();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseRouting();


            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseHangfireDashboard();
            //backgroundJobClient.Enqueue(() => serviceProvider.GetService<IRecommendService>().RefreshDiscoveryQueues());
            recurringJobManager.AddOrUpdate(
                "Refresh Discovery Queues", () => serviceProvider.GetService <IRecommendService>
                    ().RefreshDiscoveryQueues(), Cron.Daily());
        }
        /// <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);
        }
Exemple #3
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                var options = new DashboardOptions
                {
                    DashboardTitle = "PDF Splitter",
                    DisplayStorageConnectionString = false
                };

                endpoints.MapHangfireDashboard(string.Empty, options);
            });

            var            options       = new DailyCronJobOptions();
            IConfiguration configuration = app.ApplicationServices.GetService <IConfiguration>();

            configuration.GetSection(DailyCronJobOptions.DailyCronJob).Bind(options);
            string absoluteDirectoryPath = new FileInfo(options.DirectoryPath).FullName;

            RecurringJob.AddOrUpdate(
                () => CronJob.Scan(absoluteDirectoryPath),
                Cron.Daily(options.Hour, options.Minute));
        }
Exemple #4
0
        /// <summary>
        /// </summary>
        protected override void OnModuleStarting()
        {
            _thisModule = this;

            var taskSchedulingManager = AppCore.Get <TaskSchedulingManager>();
            var task = taskSchedulingManager.RegisterTask(new TaskRequest()
            {
                Name            = "Обслуживание индексов",
                Description     = "",
                IsEnabled       = true,
                TaskOptions     = TaskOptions.AllowDisabling | TaskOptions.AllowManualSchedule | TaskOptions.PreventParallelExecution,
                UniqueKey       = $"{typeof(DbMaintenanceModule).FullName}_{nameof(MaintenanceIndexes)}",
                ExecutionLambda = () => MaintenanceIndexesStatic()
            });

            if (task.ManualSchedules.Count == 0)
            {
                taskSchedulingManager.SetTaskManualScheduleList(task, new List <TaskSchedule>()
                {
                    new TaskCronSchedule(Cron.Daily())
                    {
                        IsEnabled = true
                    }
                });
            }
        }
 public static void InitializeJobs()
 {
     RecurringJob.AddOrUpdate <SendPaymentReminder>(job => job.Execute(), Cron.Monthly(25, 12));
     RecurringJob.AddOrUpdate <SendLeaseReminder>(job => job.Execute(), Cron.Daily(12));
     RecurringJob.AddOrUpdate <testReminder>(job => job.Execute(), Cron.Daily(15));
     RecurringJob.AddOrUpdate <SendDepositReminder>(job => job.Execute(), Cron.Daily(15));
 }
Exemple #6
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)
        {
            // add these
            app.UseHangfireDashboard();
            app.UseHangfireServer();

            loggerFactory.AddFile(@"c:\logs\myapp.txt");

            // added this
            RecurringJob.AddOrUpdate <IFoo>(
                s => s.FooLog(), Cron.Daily(21, 30));
            RecurringJob.AddOrUpdate <IFoo>(
                s => s.FooLog(), Cron.Minutely);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Exemple #7
0
        /// <summary>
        /// Convert hour/minute into cron time string for Hangfire
        /// </summary>
        private static string MakeDailyCronJobStringFromLocalTime(int hour, int minute)
        {
            var now            = DateTime.Now;
            var localCrontTime = new DateTime(now.Year, now.Month, now.Day, hour, minute, 0, DateTimeKind.Local);

            return(Cron.Daily(localCrontTime.Hour, localCrontTime.Minute));
        }
Exemple #8
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);
        }
Exemple #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseHangfireDashboard();

            Jobs job = new Jobs();

            RecurringJob.AddOrUpdate(() => job.UpdateEvents(), Cron.Daily);
            RecurringJob.AddOrUpdate(() => job.SendEmailsForToday(), Cron.Daily(7, 0));
            //RecurringJob.AddOrUpdate(() => job.SendWelcomeEmail(), Cron.Daily);
            app.UseHangfireServer();

            app.UseMvc();
        }
Exemple #10
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            app.UseHangfireAspNet(GetHangfireConfiguration);
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new IDashboardAuthorizationFilter[0]
            });

            IIndicadorAutomaticoService indicadorAutomaticoService = (IIndicadorAutomaticoService)KernelNinject.GetService(typeof(IIndicadorAutomaticoService));

            indicadorAutomaticoService.GenerarJobsTareasAutomaticas();

            RecurringJob.AddOrUpdate <NotificacionService>(
                "NotificarCarga",
                x => x.NotificarCarga(),
                //Cron.Minutely);
                Cron.Monthly(1, 2, 0)); // Cada 1º de mes a las 2 a.m.

            RecurringJob.AddOrUpdate <NotificacionService>(
                "NotificarMetas",
                x => x.NotificarMetas(),
                //Cron.Minutely);
                Cron.Daily(3, 0)); // Cada día a las 3 a.m.

            RecurringJob.AddOrUpdate <AnioTableroService>(
                "ProcesoHabilitarAnioSiguiente",
                x => x.ProcesoHabilitarAnioSiguiente(),
                Cron.Yearly(12, 31, 23, 0));
        }
Exemple #11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            appHost = new AppHost(Configuration)
            {
                AppSettings = new NetCoreAppSettings(Configuration)
            };

            app.UseHangfireDashboard();

            app.UseServiceStack(appHost);



            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                Activator = new ContainerJobActivator(appHost.Container)
            });


            // JobStorage.Current = new SQLiteStorage();


            RecurringJob.AddOrUpdate <ReportService>(x => x.Any(new DailyPostViewRequest()
            {
                Date = DateTime.UtcNow.AddDays(-1)
            }), Cron.Daily(0));
        }
Exemple #12
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMiddleware <ThrottlingMiddleware>();
            app.UseMiddleware <HttpStatusExceptionMiddleware>();

            app.UseRouting();

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

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

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

            RecurringJob.AddOrUpdate <ICurrencyService>(w => w.UpdateCurrencies(), Cron.Daily(12, 0), TimeZoneInfo.Local);
        }
Exemple #13
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseDeveloperExceptionPage();

            var random              = new Random();
            var serverName          = "Test server #" + random.Next(1, 1000);
            var randomCheckInterval = TimeSpan.FromMilliseconds(random.Next(300, 2000));
            var monitors            = Process.GetProcessesByName("chrome")
                                      .Select(x => new ProcessMonitor(TimeSpan.FromMilliseconds(random.Next(300, 2000)), x))
                                      .Append(new ProcessMonitor(randomCheckInterval))
                                      .ToArray();

            app.UseHangfireServer(new BackgroundJobServerOptions
            {
                ServerName          = serverName,
                ServerCheckInterval = TimeSpan.FromSeconds(5),
                ServerTimeout       = TimeSpan.FromSeconds(15),
                HeartbeatInterval   = TimeSpan.FromSeconds(3),
                WorkerCount         = 1
            }, monitors);

            app.UseHangfireDashboard("", new DashboardOptions {
                Authorization = new IDashboardAuthorizationFilter[0]
            });
            RecurringJob.AddOrUpdate(() => Alloc(), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => CpuKill(75), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => GC.Collect(2), Cron.Daily(), TimeZoneInfo.Utc);
            RecurringJob.AddOrUpdate(() => AggregateTest(), Cron.Daily(), TimeZoneInfo.Utc);
        }
Exemple #14
0
        public void Initialized(InitializedContext context)
        {
            var settingJsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data", "setting.json");
            var options         = new SystemOptions();

            if (File.Exists(settingJsonPath))
            {
                options = JsonConvert.DeserializeObject <SystemOptions>(File.ReadAllText(settingJsonPath));
            }
            SystemOptions.Instance = options;
            // 在本地地址上启动Web服务,可以根据需求改变端口
            _webHost.StartAsync(options.HangdireDashboardUri, _mahuaApi.GetSourceContainer());

            // 定时记录资产
            RecurringJob.AddOrUpdate(nameof(IUserAssetTracer), () => _userAssetTracer.Recode(), Cron.MinuteInterval(10));

            // 定时检测订单成交变化
            RecurringJob.AddOrUpdate(nameof(OrderTracer), () => _orderTracer.ReportFinishedOrders(), () => Cron.MinuteInterval(5));

            // 定时报告资产变化
            foreach (var hour in HoursInChina)
            {
                RecurringJob.AddOrUpdate(nameof(IUserAssetTracer) + hour,
                                         () => _userAssetTracer.Report(), () => Cron.Daily((hour - 8 + 24) % 24));
            }

            Process.Start($"{options.HangdireDashboardUri}/hangfire/recurring");
        }
Exemple #15
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.");
            }
        }
        public async Task ScheduleAsync_DeleteSchedulesThatExistButHaveDifferentCronExpressions()
        {
            // Arrange
            var name              = BaseValueGenerator.Word();
            var queueName         = Default.Queue;
            var cron              = Cron.Daily();
            var payload           = Guid.NewGuid().ToByteArray();
            var command           = new BasicCommand();
            var cancellationToken = CancellationToken.None;
            var existingItem      = new ScheduleItem
            {
                Id             = Guid.NewGuid(),
                CronExpression = Cron.Weekly().Expression,
                Name           = name,
                Payload        = Guid.NewGuid().ToByteArray(),
                Queue          = queueName
            };

            _payloadSerializer.SerializeAsync(command, cancellationToken).Returns(Task.FromResult(payload));
            _scheduleProviderFactory.CreateAsync(queueName, cancellationToken).Returns(Task.FromResult(_scheduleProvider));
            _scheduleProvider.LoadByNameAsync(name, cancellationToken).Returns(Task.FromResult(existingItem));

            // Act
            await _sut.ScheduleAsync(name, command, Cron.Daily(), cancellationToken);

            // Assert
            await _scheduleProvider.Received(1).DeleteAsync(existingItem.Id, cancellationToken);

            await _scheduleProvider.Received(1).CreateAsync(Arg.Is <ScheduleItem>(x => x.Queue == queueName && x.CronExpression == cron.Expression), cancellationToken);
        }
Exemple #17
0
        public void Configuration(IAppBuilder app)
        {// Storage is the only thing required for basic configuration.
            ConfigureAuth(app);
            // Just discover what configuration options do you have.
            var optionsServer = new BackgroundJobServerOptions
            {
                Queues = new[] { "ahigh", "clow", "default" }
            };

            GlobalConfiguration.Configuration
            .UseSqlServerStorage(@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Hangfire.mdf;Initial Catalog=Hangfire;Integrated Security=True");
            //.UseActivator(...)
            //.UseLogProvider(...)

            app.UseHangfireServer(optionsServer);
            app.UseHangfireDashboard("/Dashboard", new DashboardOptions()
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            }

                                     );

            RecurringJob.AddOrUpdate(() => IndexCRUD.AddUpdateLuceneIndex(Path.Combine(GlobalVariables.MyAppPath, "UsersData")), Cron.Weekly(System.DayOfWeek.Saturday, 1)); //update ındex weekly check If files deleted or added outsite of site
            RecurringJob.AddOrUpdate(() => IndexCRUD.Optimize(), Cron.Daily(2));                                                                                             //optimize index every day
        }
Exemple #18
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结束程序!");
                    }
                }
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //HangFire
            //       app.UseHangfireDashboard();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new MyAuthorizationFilter() },
            });
            app.UseHangfireServer();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            IServiceProvider    servicesProvider = _services.BuildServiceProvider();
            IHangFireJobService hngfirSrvc       = servicesProvider.GetRequiredService <IHangFireJobService>();
            IHangFireJobService hngfirSrvc2      = servicesProvider.GetRequiredService <IHangFireJobService>();

            RecurringJob.AddOrUpdate(() => hngfirSrvc2.NotifyUnreadedUsers(), Cron.HourInterval(2));
            RecurringJob.AddOrUpdate(() => hngfirSrvc.UpdateKhatmaCountHangfire(), Cron.Daily(02));
            //  RecurringJob.AddOrUpdate(() => hngfirSrvc2.NotifyUnreadedUsers(), "0 0 */4 * **");
        }
Exemple #20
0
 public static void SchedulerReccuringJobs()
 {
     RecurringJob.RemoveIfExists(nameof(Job));
     RecurringJob.AddOrUpdate <Job>(nameof(Job),
                                    job => job.Run(JobCancellationToken.Null),
                                    Cron.Daily(12, 0), TimeZoneInfo.Local);
 }
Exemple #21
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              IPhoebusService _phoebusService,
                              IIntermeioService _intermeioService,
                              IAnaliseService _analiseService,
                              IPosService _posService,
                              IExtratoService _extratoService)
        {
            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.UseHangfireDashboard();
            app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
            app.UseAuthentication();
            app.UseMvc();

            #region Background Jobs HangFire
            BackgroundJob.Schedule(() => _phoebusService.RequestPhoebus(DateTime.Now, "00:00:00", "23:59:59"), TimeSpan.FromMinutes(60));
            RecurringJob.AddOrUpdate(() => _intermeioService.GetAllBaseIntermeio(), Cron.Daily(12, 30));
            RecurringJob.AddOrUpdate(() => _analiseService.ValidationAnalise(), Cron.Daily(12, 30));
            RecurringJob.AddOrUpdate(() => _posService.RequestPosByIntermeio(), Cron.Daily(12, 30));
            RecurringJob.AddOrUpdate(() => _extratoService.ValidationAluguel(), Cron.Daily(12, 30));
            #endregion
        }
Exemple #22
0
        public void Daily_WithMinuteAndHour_ReturnsFormattedStringWithHourAndMinute()
        {
            string expected = "5 5 * * *";
            string actual   = Cron.Daily(5, 5);

            Assert.Equal(expected, actual);
        }
        /// <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);
        }
Exemple #24
0
        public void Daily_WithoutMinuteOrHour_ReturnsFormattedStringWithDefaults()
        {
            string expected = "0 0 * * *";
            string actual   = Cron.Daily();

            Assert.Equal(expected, actual);
        }
Exemple #25
0
        public void Daily_WithoutMinute_ReturnsFormattedStringWithHourAndZeroMinute()
        {
            string expected = "0 5 * * *";
            string actual   = Cron.Daily(5);

            Assert.Equal(expected, actual);
        }
Exemple #26
0
        public void GetDescription_CronDailyWithHourMinute_ReturnsAtFiveFifteenAM()
        {
            string expected = "At 05:15 AM";
            string actual   = Cron.GetDescription(Cron.Daily(5, 15));

            Assert.Equal(expected, actual);
        }
Exemple #27
0
        public void GetDescription_CronDailyWithHour_ReturnsAtFiveAM()
        {
            string expected = "At 05:00 AM";
            string actual   = Cron.GetDescription(Cron.Daily(5));

            Assert.Equal(expected, actual);
        }
Exemple #28
0
        public void GetDescription_CronDaily_ReturnsAtMidnight()
        {
            string expected = "At 00:00 AM";
            string actual   = Cron.GetDescription(Cron.Daily());

            Assert.Equal(expected, actual);
        }
Exemple #29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IBackgroundJobClient bckjobclient, IRecurringJobManager rcringjobManager, IServiceProvider srvcprovider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

            app.UseHangfireDashboard();
            bckjobclient.Enqueue(() => Console.WriteLine("First job Hangfire"));
            rcringjobManager.AddOrUpdate(
                "",
                () => srvcprovider.GetService <IDatabaseSheduller>().DbFetchSheduller(),
                // "* * * * *"
                Cron.Daily()
                );
        }
Exemple #30
0
 /// <summary>
 /// hangfire初始化
 /// </summary>
 public static void Start()
 {
     RecurringJob.AddOrUpdate(() => CheckLinks(), "0 */5 * * *");                                          //每5h检查友链
     RecurringJob.AddOrUpdate(() => EverydayJob(), Cron.Daily(5), TimeZoneInfo.Local);                     //每天的任务
     RecurringJob.AddOrUpdate(() => EveryweekJob(), Cron.Weekly(DayOfWeek.Monday, 5), TimeZoneInfo.Local); //每周的任务
     RecurringJob.AddOrUpdate(() => EveryHourJob(), Cron.Hourly);                                          //每小时的任务
     BackgroundJob.Enqueue(() => HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(HangfireBackJob.StatisticsSearchKeywords), "default"));
 }