Exemplo n.º 1
0
        //todo:lhl 启动时日志无法记录;
        public Task ExecuteAsync(CancellationToken cancellationToken = default)
        {
            _recurringJobManager.AddOrUpdate("成本-->AddCostHistoryAndVer",
                                             Hangfire.Common.Job.FromExpression(() => AddCostHistoryAndVer()),
                                             _config["JobCrons:AddCostHistoryAndVer"], TimeZoneInfo.Local);

            _recurringJobManager.AddOrUpdate("成本-->AccountSplit",
                                             Hangfire.Common.Job.FromExpression(() => AccountSplit()),
                                             _config["JobCrons:DoInSplit"], TimeZoneInfo.Local);

            _recurringJobManager.AddOrUpdate("费用-->AddExpenseHistory",
                                             Hangfire.Common.Job.FromExpression(() => AddExpenseHistory()),
                                             _config["JobCrons:AddExpenseHistory"], TimeZoneInfo.Local);

            _recurringJobManager.AddOrUpdate("费用-->ExpenseSplit",
                                             Hangfire.Common.Job.FromExpression(() => ExpenseSplit()),
                                             _config["JobCrons:ExpenseSplit"], TimeZoneInfo.Local);

            _recurringJobManager.AddOrUpdate("Account测试",
                                             Hangfire.Common.Job.FromExpression(() => Test()),
                                             "0 0 0/1 * * ? ", TimeZoneInfo.Local);


            return(Task.CompletedTask);
        }
Exemplo n.º 2
0
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _backgroundJobs.Enqueue <Services>(x => x.LongRunning(JobCancellationToken.Null));

                //  [NotNull] string recurringJobId, [NotNull] Job job, [NotNull] string cronExpression, [NotNull] RecurringJobOptions options

                _recurringJobs.AddOrUpdate("seconds", () => TestAsync(), "*/15 * * * * *");
                //_recurringJobs.AddOrUpdate("minutely", () => Console.WriteLine("Hello, world!"), Cron.Minutely);
                //_recurringJobs.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *");

                //_recurringJobs.AddOrUpdate("neverfires", () => Console.WriteLine("Can only be triggered"), "0 0 31 2 *");

                //_recurringJobs.AddOrUpdate("Hawaiian", () => Console.WriteLine("Hawaiian"), "15 08 * * *", TimeZoneInfo.FindSystemTimeZoneById("Hawaiian Standard Time"));
                //_recurringJobs.AddOrUpdate("UTC", () => Console.WriteLine("UTC"), "15 18 * * *");
                _recurringJobs.AddOrUpdate("Russian", () => Console.WriteLine("Russian"), "15 21 * * *", TimeZoneInfo.Local);

                // http call
                // RecurringJob.AddOrUpdate(() => TestAsync(), Cron.Minutely());
            }
            catch (Exception e)
            {
                _logger.LogError("An exception occurred while creating recurring jobs.", e);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 3
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 backgroundJobClient,
                              IRecurringJobManager recurringJobManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

            app.UseHangfireDashboard();
            backgroundJobClient.Enqueue(() => Console.WriteLine("This is my first Hangfire Job"));
            recurringJobManager.AddOrUpdate("Recurring-Every-Minute", () => Console.WriteLine("EveryMinute"), "* * * * *");
            recurringJobManager.AddOrUpdate("Recurring-Every-Second", () => Console.WriteLine("EverySeconds"), "*/01 * * * * *");
        }
Exemplo n.º 4
0
        public static void RegisterHangfireApp(this IApplicationBuilder app,
                                               IBackgroundJobClient backgroundJobClient,
                                               IRecurringJobManager recurringJobManager,
                                               IServiceProvider serviceProvider)
        {
            app.UseHangfireServer();
            app.UseHangfireDashboard("/hangfire");

            recurringJobManager.AddOrUpdate(
                "Remove Violence Post",
                () => serviceProvider.GetService <IHangfireService>().RemoveViolencePost(),
                Cron.Minutely
                );

            recurringJobManager.AddOrUpdate(
                "Remove Violence Comment",
                () => serviceProvider.GetService <IHangfireService>().RemoveViolenceComment(),
                Cron.Minutely
                );

            recurringJobManager.AddOrUpdate(
                "Remove Violence Reply Comment",
                () => serviceProvider.GetService <IHangfireService>().RemoveViolenceReply(),
                Cron.Minutely
                );
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              IRecurringJobManager recurringJobManager,
                              IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            var employeeService = serviceProvider.GetService <IEmployeeService>();

            recurringJobManager.AddOrUpdate("Get_All_Employees", () => employeeService.PrintAllEmployeeTitles(), Cron.Minutely);
            recurringJobManager.AddOrUpdate("Disable_All_Employees", () => employeeService.DisableAllEmployees(), Cron.Minutely);
        }
Exemplo n.º 6
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IRecurringJobManager recurringJobManager,
                              IServiceProvider serviceProvider)
        {
            var section = Configuration.GetSection(nameof(IntegrationAppSettings));
            var integrationAppSettings = section.Get <IntegrationAppSettings>();

            string        userlist;
            List <string> UserNames = new List <string>();
            SFDCAction    sfdca     = new SFDCAction(integrationAppSettings);

            UserNames = sfdca.GetAllDriverInfo_NotMappedSFDC();
            userlist  = "'" + string.Join("','", UserNames.Where(k => !string.IsNullOrEmpty(k))) + "'";

            FleetCompleteAction fca = new FleetCompleteAction(integrationAppSettings);
            var url       = "https://hosted.fleetcomplete.com.au/Authentication/v9/Authentication.svc/authenticate/user?clientId=" + 46135 + "&userLogin="******"&userPassword="******"/swagger/v1/swagger.json", "My API V1");
            });
            app.UseHangfireDashboard();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            recurringJobManager.AddOrUpdate(
                "Scheduled Customer Service Line",
                () => serviceProvider.GetService <ISFDC>().IntegerateSfCustServiceLine(integrationAppSettings.SFDCUserName, integrationAppSettings.SFDCUserPassword),
                integrationAppSettings.CSLineScheduleTime, TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time")
                );
            recurringJobManager.AddOrUpdate(
                "Scheduled Customer List",
                () => serviceProvider.GetService <ISFDC>().IntegerateSfCustomeList(integrationAppSettings.SFDCUserName, integrationAppSettings.SFDCUserPassword),
                integrationAppSettings.CustomerListScheduleTime, TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time")
                );
            recurringJobManager.AddOrUpdate(
                "Scheduled Driver",
                () => serviceProvider.GetService <ISFDC>().IntegrateSFDCId_OperatortoDB(userlist, integrationAppSettings.SFDCUserName, integrationAppSettings.SFDCUserPassword),
                integrationAppSettings.DriverScheduleTime, TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time")
                );
            recurringJobManager.AddOrUpdate(
                "Scheduled Fleet complete asset",
                () => serviceProvider.GetService <IFleetComplete>().IntegrateAsset(integrationAppSettings.ClientID, tokeninfo.UserId, tokeninfo.Token),
                integrationAppSettings.FCAssetScheduleTime, TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time")
                );
            recurringJobManager.AddOrUpdate(
                "Scheduled Connx Driver",
                () => serviceProvider.GetService <IConnex>().IntegrateDriverDetails(integrationAppSettings.ConnexUserName, integrationAppSettings.ConnexUserPassword),
                integrationAppSettings.ConnxScheduleTime, TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time")
                );
        }
Exemplo n.º 7
0
        private void SeedHangfireJobs(IRecurringJobManager recurringJobManager)
        {
            // Edit recommended friend list for each user
            recurringJobManager
            .AddOrUpdate <RecommendedFriends>(
                "RecommendedFriends",
                x => x.AddRecomendedFrinds(),
                Cron.Weekly);

            // Delete all follow-unfollow activities
            recurringJobManager
            .AddOrUpdate <UserFollowActivitiesDbUsage>(
                "UserActivitiesDbSavage",
                x => x.DeleteFollowActivites(),
                Cron.Monthly);

            // Delete all user activities
            recurringJobManager
            .AddOrUpdate <AllActivities>("AllActivities", x => x.DeleteAllActivites(), Cron.Yearly);

            // Delete all chat messages
            recurringJobManager
            .AddOrUpdate <DeleteMessages>("DeleteMessages", x => x.DeleteAllChatMessages(), Cron.Yearly);

            // Delete all user notification
            recurringJobManager
            .AddOrUpdate <NotificationDbUsage>("DeleteNotifications", x => x.DeleteNotifications(), Cron.Yearly);
        }
Exemplo n.º 8
0
        private void SetupBackgroundJobs(IRecurringJobManager recurringJobs)
        {
            recurringJobs.AddOrUpdate("CleanApplicationLog", Job.FromExpression <BackgroundJobHelper>(x => x.CleanApplicationLog()), "0 8 * * SAT");

            recurringJobs.AddOrUpdate("RescanDirectories", Job.FromExpression <BackgroundJobHelper>(x => x.RescanDirectories()), "0 23 * * *");

            recurringJobs.AddOrUpdate("DeleteOldDirectoriesAndFiles", Job.FromExpression <BackgroundJobHelper>(x => x.DeleteOldDirectoriesAndFiles()), "0 23 * * *");
        }
Exemplo n.º 9
0
 public Task CurrencyService()
 {
     _recurringJobManager.AddOrUpdate(
         "CurrencyService",
         () => UpdateCurrencies(),
         "*/45 * * * *");
     return(Task.CompletedTask);
 }
        public void FireJob()
        {
            _recurringJobManager.AddOrUpdate("Hello World", () => Console.WriteLine("Hello world from Hangfire!"), Cron.Hourly);

            _recurringJobManager.AddOrUpdate("BtcTurk Data Async", () => _btcTurkServices.GetCoinsAsync(), "1 * * * *");

            //_backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));
        }
Exemplo n.º 11
0
 public Task StartAsync(CancellationToken cancellationToken)
 {
     _recurringJobManager.AddOrUpdate <IPBJobsRunner>("sync new comments",
                                                      runner => runner.SyncNewCommentsAsync(), "*/5 * * * *");
     _recurringJobManager.AddOrUpdate <IPBJobsRunner>("sync all comments",
                                                      runner => runner.SyncAllCommentsAsync(), "0 0 * * *");
     return(Task.CompletedTask);
 }
        public static IApplicationBuilder UseAndConfigureHangfire(this IApplicationBuilder app, IRecurringJobManager recurringJobs, IConfiguration config)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (recurringJobs == null)
            {
                throw new ArgumentNullException(nameof(recurringJobs));
            }

            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            var backgroundJobSettings = config.GetSection(ConfigurationKeys.BackgroundJobs).Get <BackgroundJobSettings>();

            app.UseHangfireServer(additionalProcesses: new[] { new ProcessMonitor(TimeSpan.FromSeconds(1.5)) });
            app.UseHangfireDashboard(
                "/hangfire",
                new DashboardOptions
            {
                DashboardTitle = $"{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductName} - {config.GetEnvironment()} ({Assembly.GetExecutingAssembly().GetName().Version})",
                Authorization  = new[] { new DashboardAuthorizationFilter(config) }
            }
                );

            if (backgroundJobSettings.PullAuctionDataBackgroundJob.Enabled)
            {
                recurringJobs.AddOrUpdate <PullAuctionDataBackgroundJob>(nameof(PullAuctionDataBackgroundJob), job => job.PullAuctionData(null !), backgroundJobSettings.PullAuctionDataBackgroundJob.Schedule);
            }
            else
            {
                recurringJobs.RemoveIfExists(nameof(PullAuctionDataBackgroundJob));
            }

            if (backgroundJobSettings.RemoveOldDataBackgroundJob.Enabled)
            {
                recurringJobs.AddOrUpdate <RemoveOldDataBackgroundJob>(nameof(RemoveOldDataBackgroundJob), job => job.RemoveOldData(null !), backgroundJobSettings.RemoveOldDataBackgroundJob.Schedule);
            }
            else
            {
                recurringJobs.RemoveIfExists(nameof(RemoveOldDataBackgroundJob));
            }

            if (backgroundJobSettings.PullRealmDataBackgroundJob.Enabled)
            {
                recurringJobs.AddOrUpdate <PullRealmDataBackgroundJob>(nameof(PullRealmDataBackgroundJob), job => job.PullRealmData(null !), backgroundJobSettings.PullRealmDataBackgroundJob.Schedule);
            }
            else
            {
                recurringJobs.RemoveIfExists(nameof(PullRealmDataBackgroundJob));
            }

            return(app);
        }
Exemplo n.º 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IRecurringJobManager recurringJobManager)
        {
            AutoMapperConfig.RegisterMappings(typeof(ErrorViewModel).GetTypeInfo().Assembly);

            // Seed data on application startup
            using (var serviceScope = app.ApplicationServices.CreateScope())
            {
                var dbContext = serviceScope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                dbContext.Database.Migrate();
                new ApplicationDbContextSeeder().SeedAsync(dbContext, serviceScope.ServiceProvider).GetAwaiter().GetResult();

                recurringJobManager.AddOrUpdate <UpdateRecommenderModelJob>("Update Recommender", x => x.Work(env.WebRootPath), Cron.Daily);
                recurringJobManager.AddOrUpdate <CancelOldProcessingOrdersJob>("Cancel Processing Orders", x => x.Work(), "*/5 * * * *");
            }

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

            app.UseStatusCodePagesWithReExecute("/Home/StatusCodePage", "?code={0}");

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

            app.UseRouting();

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

            if (env.IsProduction())
            {
                app.UseHangfireServer();
                app.UseHangfireDashboard(
                    "/Administration/Hangfire",
                    new DashboardOptions {
                    Authorization = new[] { new HangfireAuthorizationFilter() }
                });
            }

            app.UseSession();

            app.UseEndpoints(
                endpoints =>
            {
                endpoints.MapHub <ChatHub>("/chat");
                endpoints.MapControllerRoute("areaRoute", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 14
0
        private void SeedHangfireJobs(IRecurringJobManager recurringJobManager)
        {
            recurringJobManager.AddOrUpdate <InsurancesPoliciesService>("SetExpiredInsurancePoliciesLogic",
                                                                        x => x.SetExpiredInsurancePoliciesLogicAsync(), Cron.Daily);
            recurringJobManager.AddOrUpdate <VignettesService>("SetExpiredVignetteLogic",
                                                               x => x.SetVignetteExpireLogicAsync(), Cron.Daily);

            recurringJobManager.AddOrUpdate <ExpireEmailService>("SendingExpireMessage",
                                                                 x => x.ProcessAndSendingExpireMessages(), Cron.Daily(8));
        }
Exemplo n.º 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, IBackgroundJobClient backgroundJobs, IRecurringJobManager recurringJob, ApplicationDbContext context)
        {
            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.UseRouting();

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                    {
                        RequireSsl         = false,
                        SslRedirect        = false,
                        LoginCaseSensitive = true,
                        Users = new []
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login         = Configuration.GetValue <string>("HangFire:Username"),
                                PasswordClear = Configuration.GetValue <string>("HangFire:Password"),
                            }
                        }
                    }) }
            });

            var cron = new CronHelpers(context);

            recurringJob.AddOrUpdate("CleanInvestmentsJob", Job.FromExpression(() => cron.AwardInvestmentProfits()), Cron.Daily(17));
            recurringJob.AddOrUpdate("CleanEspionagesJob", Job.FromExpression(() => cron.RemoveEspionageInvestments()), Cron.Daily(17));

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

            app.UseOpenApi();
            app.UseSwaggerUi3();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
        }
Exemplo n.º 16
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 backgroundJobClient, IRecurringJobManager recurringJobManager, IServiceProvider serviceProvider)
        {
            //Stripe Payment
            StripeConfiguration.SetApiKey(Configuration.GetSection("Stripe")["SecretKey"]);

            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();
            //Rate limit to prevet overloading of the system
            app.UseIpRateLimiting();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            //Create user roles
            CreateUserRoles(serviceProvider).Wait();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });
            RotativaConfiguration.Setup(env.ContentRootPath, "wwwroot/Rotativa");
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new[] { new HangfireAuthorizationFilter() }
            });
            app.UseHangfireDashboard();
            var options = new BackgroundJobServerOptions {
                WorkerCount = 1
            };

            app.UseHangfireServer(options);
            //Clear Appointment at 8 Pm
            recurringJobManager.AddOrUpdate <JobScheduling>("Clear Appointment", x => x.ClearAppointment(), Cron.Daily(14, 00));
            //Generate report at 9 PM
            int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);

            recurringJobManager.AddOrUpdate <JobScheduling>("Generate daily report", x => x.GenerateDailyReport(), Cron.Daily(15, 00));
            recurringJobManager.AddOrUpdate <JobScheduling>("Generate Monthly report", x => x.GenerateMonthlyReport(), Cron.Monthly(days, 15));
        }
Exemplo n.º 17
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider sp, IRecurringJobManager jobManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseMiddleware <ApplicationInsightsMiddleware>();
            app.UseStaticFiles();

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

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();

                endpoints.MapGet($"/jobs/{nameof(NotificationSenderJob)}", context =>
                                 ActivatorUtilities.CreateInstance <NotificationSenderJob>(context.RequestServices).SendNotifications());

                endpoints.MapGet($"/jobs/{nameof(RetentionJob)}", context =>
                                 ActivatorUtilities.CreateInstance <RetentionJob>(context.RequestServices).RemoveOldAttachments());
            });

            //Hangfire
            jobManager.AddOrUpdate("",
                                   () => ActivatorUtilities.CreateInstance <NotificationSenderJob>(sp).SendNotifications()
                                   , Cron.Daily);

            jobManager.AddOrUpdate("",
                                   () => ActivatorUtilities.CreateInstance <RetentionJob>(sp).RemoveOldAttachments()
                                   , Cron.Daily);

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

            //swagger
            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/docs/swagger.json", "API Documentation");
                x.DefaultModelsExpandDepth(-1);
            });
        }
Exemplo n.º 18
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory,
                              IRecurringJobManager recurringJobManager, MeredithDbContext dbContext)
        {
            app.UseForwardedHeaders();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                loggerFactory.AddRollbarDotNetLogger(app.ApplicationServices);
            }

            app.UseDbContext(dbContext);

            app.UseCustomLocalization();

            app.UseCustomSwagger();

            app.UseMiddleware <ExceptionHandlingMiddleware>();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseCors();

            app.UseCustomAuthentication();
            app.UseAuthorization();

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

                endpoints.MapHangfireDashboard(new DashboardOptions
                {
                    Authorization = new IDashboardAuthorizationFilter[] { }
                })
                .RequireAuthorization(Policies.Developer);
            });

            app.UseHangfireDashboard();

            recurringJobManager.AddOrUpdate <JumpStartJob>(JumpStartJob.Id,
                                                           job => job.SendAsync(),
                                                           JumpStartJob.CronExpression, TimeZoneInfo.Utc);

            recurringJobManager.AddOrUpdate <NewJumpStartJob>(NewJumpStartJob.Id,
                                                              job => job.SendAsync(),
                                                              NewJumpStartJob.CronExpression, TimeZoneInfo.Utc);
        }
Exemplo n.º 19
0
        private void RegisterJobs(IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.CreateScope())
            {
                var sp = scope.ServiceProvider;
                var hangfireJobType = typeof(HangfireJob);
                foreach (var assembly in _contribOptions.ScanningAssemblies)
                {
                    foreach (var candidate in assembly.ExportedTypes)
                    {
                        if (candidate.IsAbstract)
                        {
                            // Skip abstract types
                            continue;
                        }

                        if (hangfireJobType.IsAssignableFrom(candidate) && candidate != hangfireJobType)
                        {
                            try
                            {
                                var jobInstance = (HangfireJob)ActivatorUtilities.CreateInstance(sp, candidate);
                                if (!string.IsNullOrEmpty(jobInstance.Schedule))
                                {
                                    _logger.LogInformation("Auto-scheduling job {JobName} with schedule {JobSchedule}", candidate.Name, jobInstance.Schedule);
                                    _recurringJobManager.AddOrUpdate(
                                        candidate.Name,
                                        new Job(candidate, _executeMethod, null, null),
                                        jobInstance.Schedule);
                                }
                                else
                                {
                                    _logger.LogDebug("Job {JobName} auto-scheduling is disabled", candidate.Name);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw new InvalidOperationException($"Unable to activate job {hangfireJobType.Name}. Probably due to missing dependencies. See inner exception for more details.", ex);
                            }
                        }
                        else
                        {
                            var scheduleAttr = candidate.GetCustomAttribute <AutoScheduleAttribute>();
                            if (scheduleAttr != null)
                            {
                                _logger.LogInformation("Auto-scheduling job {JobName} via [AutoScheduled] attribute with schedule {JobSchedule}", candidate.Name, scheduleAttr.CronExpression);
                                _recurringJobManager.AddOrUpdate(candidate.Name, new Job(candidate, candidate.GetMethod(scheduleAttr.MethodName)), scheduleAttr.CronExpression);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        public void InitJobs()
        {
            var jobSchedules = _schedulerService.GetJobSchedules().GetAwaiter().GetResult();

            foreach (var jobSchedule in jobSchedules.ToArray().AsParallel())
            {
                _recurringJobManager.AddOrUpdate(jobSchedule.Cron,
                                                 () => _notificationJob.Execute(jobSchedule.FireTime),
                                                 jobSchedule.Cron);
            }
            // todo: визначити, що відбувається, коли у студента обрані кілька предметів на даний час
            this._jobSchedules = jobSchedules.ToArray();
        }
Exemplo n.º 21
0
        private void SeedHangfireJobs(IRecurringJobManager recurringJobManager, ApplicationDbContext dbContext)
        {
            recurringJobManager.AddOrUpdate <DbCleanupJob>("DbCleanupJob", x => x.Work(), Cron.Weekly);
            recurringJobManager.AddOrUpdate <MainNewsGetterJob>("MainNewsGetterJob", x => x.Work(null), "*/2 * * * *");
            var sources = dbContext.Sources.Where(x => !x.IsDeleted).ToList();

            foreach (var source in sources)
            {
                recurringJobManager.AddOrUpdate <GetLatestPublicationsJob>(
                    $"GetLatestPublicationsJob_{source.Id}_{source.ShortName}",
                    x => x.Work(source.TypeName, null),
                    "*/5 * * * *");
            }
        }
Exemplo n.º 22
0
        private void SeedHangfireJobs(IRecurringJobManager recurringJobManager)
        {
            recurringJobManager
            .AddOrUpdate <DeleteChatMessages>(
                "DeleteChatMessages", x => x.DeleteAsync(), Cron.Daily);

            recurringJobManager
            .AddOrUpdate <DeleteAppointments>(
                "DeletePastAppointmentsAsync", x => x.DeletePastAppointmentsAsync(), Cron.Daily);

            recurringJobManager
            .AddOrUpdate <DeleteAppointments>(
                "DeleteCancelledAppointmentsAsync", x => x.DeleteCancelledAppointmentsAsync(), Cron.Daily);
        }
Exemplo n.º 23
0
 private void InstanciarJobsHangFire(IRecurringJobManager recurringJobManager)
 {
     recurringJobManager.AddOrUpdate <EnviarEmailParaEnvioNfJob>("solicitar-envio-nf-prestador", x => x.Execute(), "20 11 * * *");
     recurringJobManager.AddOrUpdate <AtualizarImportacaoPagamentoRMJob>("atualizar-status-pagamento-prestador", x => x.Execute(), "00 */2 * * *");
     recurringJobManager.AddOrUpdate <EnviarEmailParaAprovacaoHorasJob>("solicitar-aprovacao-horas-prestador", x => x.Execute(), "00 11 * * *");
     recurringJobManager.AddOrUpdate <AtualizarInformacaoCelulaJob>("atualizar-informacao-celula", x => x.Execute(), "00 9 * * *");
     recurringJobManager.AddOrUpdate <AtualizarMigracaoPessoaJob>("atualizar-migracao-pessoa", x => x.Execute(), "00 9 * * *");
     recurringJobManager.AddOrUpdate <RealizarTransferenciaPrestadorJob>("efetivar-transferencias-prestadores", x => x.Execute(), "00 2 * * *");
     recurringJobManager.AddOrUpdate <RealizarFinalizacaoContratosJob>("efetivar-finalizacao-contratos", x => x.Execute(), "00 2 * * *");
     recurringJobManager.AddOrUpdate <MigrarProfissionaisNatcorpJob>("efetivar-finalizacao-contratos", x => x.Execute(), "00 */1 * * *");
     recurringJobManager.AddOrUpdate <RealizarReajusteContratosJob>("Efetivar-reajuste-contratos", x => x.Execute(), "00 2 * * *");
     //TO_DO testar
     recurringJobManager.AddOrUpdate <MigrarTodosProfissionaisNatcorpJob>("efetivar-finalizacao-contratos", x => x.Execute(), "00 2 * * *");
 }
Exemplo n.º 24
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 backgroundJobClient,
            IRecurringJobManager recurringJobManager,
            IServiceProvider serviceProvider
            )
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            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.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            /* Hangfire Server Setup */
            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                Authorization = new [] { new MyAuthorizationFilter() }
            });
            backgroundJobClient.Enqueue(() => Console.WriteLine("Hangfire online."));
            backgroundJobClient.Enqueue(() => serviceProvider.GetService <ISeeder>().Seed());
            recurringJobManager.AddOrUpdate(
                "Auto-Delete",
                () => serviceProvider.GetService <IDeleteService>().CleanRecordsASync(),
                Cron.Hourly
                );
            recurringJobManager.AddOrUpdate(
                "Reset",
                () => serviceProvider.GetService <ISeeder>().Seed(),
                "*/30 * * * *"
                );
        }
Exemplo n.º 25
0
        public Task ExecuteAsync()
        {
            _recurringJobManager.AddOrUpdate("check-link", Job.FromExpression <Job1>(m => m.Execute()), Cron.Minutely(), new RecurringJobOptions());
            _recurringJobManager.Trigger("check-link");

            return(Task.CompletedTask);
        }
Exemplo n.º 26
0
        public static void AddOrUpdate(
            [NotNull] this IRecurringJobManager manager,
            [NotNull] string recurringJobId,
            [NotNull] Job job,
            [NotNull] string cronExpression,
            [NotNull] TimeZoneInfo timeZone,
            [NotNull] string queue)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (timeZone == null)
            {
                throw new ArgumentNullException(nameof(timeZone));
            }
            if (queue == null)
            {
                throw new ArgumentNullException(nameof(queue));
            }

            manager.AddOrUpdate(
                recurringJobId,
                job,
                cronExpression,
                new RecurringJobOptions {
                QueueName = queue, TimeZone = timeZone
            });
        }
Exemplo n.º 27
0
        public static void AddOrUpdate <T>(
            [NotNull] this IRecurringJobManager manager,
            [NotNull] string recurringJobId,
            [NotNull] Expression <Func <T, Task> > methodCall,
            [NotNull] string cronExpression,
            TimeZoneInfo timeZone = null,
            string queue          = EnqueuedState.DefaultQueue)
        {
            if (manager == null)
            {
                throw new ArgumentNullException(nameof(manager));
            }
            if (recurringJobId == null)
            {
                throw new ArgumentNullException(nameof(recurringJobId));
            }
            if (methodCall == null)
            {
                throw new ArgumentNullException(nameof(methodCall));
            }
            if (cronExpression == null)
            {
                throw new ArgumentNullException(nameof(cronExpression));
            }

            var job = Job.FromExpression(methodCall);

            manager.AddOrUpdate(recurringJobId, job, cronExpression, timeZone ?? TimeZoneInfo.Utc, queue);
        }
Exemplo n.º 28
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()
                );
        }
Exemplo n.º 29
0
 private void SeedHangfireJobs(IRecurringJobManager recurringJobManager, ApplicationDbContext dbContext, IServiceProvider serviceProvider)
 {
     recurringJobManager.AddOrUpdate(
         "UpdateConsultationsOnCompletedTime",
         () => serviceProvider.GetService <IConsultationsService>().UpdateConsultationsWhenCompleted(),
         Cron.Minutely);
 }
Exemplo n.º 30
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 backgroundJobClient,
                              IRecurringJobManager recurringJobManager)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Hello World!");
                });
            });
            app.UseHangfireDashboard();
            backgroundJobClient.Enqueue(() => Console.WriteLine("Hello Hangfire job!"));
            recurringJobManager.AddOrUpdate(
                "Run every minute",
                () => Console.WriteLine("Test recurring job"),
                "* * * * *"
                );
        }