// 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.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/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.UseHangfireDashboard();

            var manager = new RecurringJobManager();

            manager.AddOrUpdate("ReadTransactionJob", Job.FromExpression(() => Console.WriteLine("")), "*/5 * * * *");
            manager.AddOrUpdate("ReadTransactionJob2", Job.FromExpression(() => Console.WriteLine("")), "*/8 * * * *");

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

            app.UseMvc();
        }
Exemple #2
0
        public static void SetupJobs()
        {
            var manager = new RecurringJobManager();

            //manager.AddOrUpdate ("email_send", Job.FromExpression (() => EmailSend ()), Cron.Minutely ());
            manager.AddOrUpdate("tabels_create", Job.FromExpression(() => TabelsCreate()), Cron.Daily(0, 5));
            manager.AddOrUpdate("alert_users", Job.FromExpression(() => AlertUsers()), Cron.Monthly(20, 9));
            manager.AddOrUpdate("alert_managers", Job.FromExpression(() => AlertManagers()), Cron.Monthly(25, 9));
        }
Exemple #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)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

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

            app.UseRouting();
            app.UseEndpoints(routes => routes.MapDefaultControllerRoute());

            var recurringJobs = new RecurringJobManager();

            RecurringJob.AddOrUpdate <Tasks>(x => x.SuccessTask(null, null), Cron.Minutely);
            //            RecurringJob.AddOrUpdate<Tasks>(x => x.FailedTask(null, null), "*/2 * * * *");
            recurringJobs.AddOrUpdate("Failed Task", Job.FromExpression <Tasks>(x => x.FailedTask(null)), "*/2 * * * *", TimeZoneInfo.Local);

            BackgroundJob.Enqueue <BaseJob>(x => x.Run());
            BackgroundJob.Enqueue <DerivedJob>(x => x.Run());
        }
Exemple #4
0
        protected async Task CreateBuildEngineReleaseAsync(Product product, string channel)
        {
            var release = new Release
            {
                Channel = channel
            };

            ClearRecurringJob(product.Id);
            ReleaseResponse releaseResponse = null;

            if (SetBuildEngineEndpoint(product.Project.Organization))
            {
                releaseResponse = BuildEngineApi.CreateRelease(product.WorkflowJobId,
                                                               product.WorkflowBuildId,
                                                               release);
            }
            if ((releaseResponse != null) && (releaseResponse.Id != 0))
            {
                product.WorkflowPublishId = releaseResponse.Id;
                await ProductRepository.UpdateAsync(product);

                var monitorJob = Job.FromExpression <BuildEngineReleaseService>(service => service.CheckRelease(product.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(product.Id), monitorJob, "* * * * *");
            }
            else
            {
                // TODO: Send Notification
                // Throw Exception to force retry
                throw new Exception("Create release failed");
            }
        }
        protected async Task CreateBuildEngineReleaseAsync(Product product, Dictionary <string, object> paramsDictionary, PerformContext context)
        {
            var channel     = GetChannel(paramsDictionary);
            var targets     = GetTargets(paramsDictionary, "google-play");
            var environment = GetEnvironment(paramsDictionary);

            environment["PRODUCT_ID"] = product.Id.ToString();
            environment["PROJECT_ID"] = product.ProjectId.ToString();
            var release = new Release
            {
                Channel     = channel,
                Targets     = targets,
                Environment = environment
            };

            ClearRecurringJob(product.Id);
            ReleaseResponse releaseResponse = null;

            if (SetBuildEngineEndpoint(product.Project.Organization))
            {
                releaseResponse = BuildEngineApi.CreateRelease(product.WorkflowJobId,
                                                               product.WorkflowBuildId,
                                                               release);
            }
            if ((releaseResponse != null) && (releaseResponse.Id != 0))
            {
                product.WorkflowPublishId = releaseResponse.Id;
                await ProductRepository.UpdateAsync(product);

                var build = await BuildRepository.Get().Where(b => b.BuildId == product.WorkflowBuildId).FirstOrDefaultAsync();

                if (build == null)
                {
                    throw new Exception($"Failed to find ProductBuild: {product.WorkflowBuildId}");
                }
                var publish = new ProductPublication
                {
                    ProductId      = product.Id,
                    ProductBuildId = build.Id,
                    ReleaseId      = releaseResponse.Id,
                    Channel        = channel
                };
                await PublicationRepository.CreateAsync(publish);

                var monitorJob = Job.FromExpression <BuildEngineReleaseService>(service => service.CheckRelease(product.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(product.Id), monitorJob, "* * * * *");
            }
            else
            {
                var messageParms = new Dictionary <string, object>()
                {
                    { "projectName", product.Project.Name },
                    { "productName", product.ProductDefinition.Name }
                };
                await SendNotificationOnFinalRetryAsync(context, product.Project.Organization, product.Project.Owner, "releaseFailedUnableToCreate", messageParms);

                // Throw Exception to force retry
                throw new Exception("Create release failed");
            }
        }
Exemple #6
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            HangfireAspNet.Use(GetHangfireServers);


            //BackgroundJob.Enqueue(() => CrawlerJobs.RemoveAll());
            //BackgroundJob.Enqueue(() => CrawlerJobs.GetDiscounts());

            //using (var connection = JobStorage.Current.GetConnection())
            //{

            //    foreach (var recurringJob in StorageConnectionExtensions.GetRecurringJobs(connection))
            //    {
            //        RecurringJob.RemoveIfExists(recurringJob.Id);
            //    }
            //}
            // BackgroundJob.Enqueue(() => CrawlerJobs.AddGame());


            //RecurringJob.AddOrUpdate(() => CrawlerJobs.RemoveAll(), Cron.Daily);
            var manager = new RecurringJobManager();

            manager.RemoveIfExists("500");
            manager.AddOrUpdate("500", () => CrawlerJobs.GetDiscounts(), Cron.Daily);
            manager.Trigger("500");
        }
        protected async Task CreateBuildEngineProjectAsync(Project project)
        {
            var buildEngineProject = new BuildEngineProject
            {
                UserId        = project.Owner.Email,
                GroupId       = project.Group.Abbreviation,
                AppId         = project.Type.Name,
                LanguageCode  = project.Language,
                PublishingKey = project.Owner.PublishingKey,
                ProjectName   = project.Name
            };
            ProjectResponse projectResponse = null;

            if (SetBuildEngineEndpoint(project.Organization))
            {
                projectResponse = BuildEngineApi.CreateProject(buildEngineProject);
            }
            if ((projectResponse != null) && (projectResponse.Id != 0))
            {
                // Set state to active?
                project.WorkflowProjectId = projectResponse.Id;
                await ProjectRepository.UpdateAsync(project);

                var monitorJob = Job.FromExpression <BuildEngineProjectService>(service => service.ManageProject(project.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(project.Id), monitorJob, "* * * * *");
            }
            else
            {
                // TODO: Send Notification
                // Throw Exception to force retry
                throw new Exception("Create project failed");
            }
        }
Exemple #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");
            }
        }
        public static void InitializeTenants(this IApplicationBuilder app, ITenantService tenantService)
        {
            //var teervice = app.ApplicationServices.GetRequiredService <ITenantService>();
            var tenants = tenantService.GetTenants().Result;

            foreach (var tenant in tenants)
            {
                GlobalConfiguration.Configuration.UseSqlServerStorage(tenant.ConnectionString);
                var sqlStorage = new SqlServerStorage(tenant.ConnectionString);

                //var myapp = app.New();
                app.UseHangfireDashboard($"/dashboard/{tenant.Name}", new DashboardOptions
                {
                    Authorization = new[] { new HangfireAuthFilter() }
                }, sqlStorage);

                var options = new BackgroundJobServerOptions
                {
                    ServerName = string.Format("{0}.{1}", tenant.Name, Guid.NewGuid().ToString()),
                };

                var jobStorage = JobStorage.Current;

                app.UseHangfireServer(options, null, jobStorage);



                //RecurringJob.AddOrUpdate<IHangfireRecurringJobService>(j => j.CheckForAbandonedCart(), Cron.Minutely);
                var recurringJobManager = new RecurringJobManager();
                recurringJobManager.RemoveIfExists(tenant.Id.ToString());
                recurringJobManager.AddOrUpdate <IHangfireRecurringJobService>(tenant.Id.ToString(), j => j.CheckForAbandonedCart(tenant.ConnectionString), Cron.Minutely);
                recurringJobManager.Trigger(tenant.Id.ToString());
            }
        }
Exemple #10
0
        // Method creating the time-bound scheduler jobs
        public static void SendEmailDaily()
        {
            GlobalConfiguration.Configuration
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseColouredConsoleLogProvider()
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseSqlServerStorage("Server=(localdb)\\MSSQLLocalDB;Database=DBEmailScheduler;Trusted_Connection=True;", new SqlServerStorageOptions
            {
                CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
                QueuePollInterval            = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                UsePageLocksOnDequeue        = true,
                DisableGlobalLocks           = true
            });

            int hourDiff = DateTimeOffset.Now.Offset.Hours;
            int minDiff  = DateTimeOffset.Now.Offset.Minutes;

            var manager = new RecurringJobManager();

            manager.AddOrUpdate("EmailSchedulerDaily", Job.FromExpression(() => EmailSchedulerDailyJob()), Cron.Daily(hourDiff, minDiff));

            using (var server = new BackgroundJobServer())
            {
                Console.ReadLine();
            }
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IBackgroundJobClient backgroundJobs, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            /* app.ApplicationServices.UseSmartSqlSync();
             * app.ApplicationServices.UseSmartSqlSubscriber((syncRequest) =>
             * {
             *  Console.Error.WriteLine(syncRequest.Scope);
             * });*/

            app.UseMvc();



            app.UseHangfireDashboard();
            backgroundJobs.Enqueue(() => Console.WriteLine("Hello world from Hangfire!"));


            var manager = new RecurringJobManager();

            manager.AddOrUpdate("hello-world-id", () => Console.WriteLine("Hello World!"), Cron.Minutely());

            app.UseHealthChecks("/healthz", new HealthCheckOptions
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            })
            .UseHealthChecksUI();

            app.UseSwagger(c => { });
            app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Zema.Sample.AspNetCore"); });
        }
        public async Task Dispatch([NotNull] DashboardContext context)
        {
            var response = new Response()
            {
                Status = true
            };

            var job = new PeriodicJob();

            job.Id     = context.Request.GetQuery("Id");
            job.Cron   = context.Request.GetQuery("Cron");
            job.Class  = context.Request.GetQuery("Class");
            job.Method = context.Request.GetQuery("Method");
            job.Queue  = context.Request.GetQuery("Queue");

            if (!Utility.IsValidSchedule(job.Cron))
            {
                response.Status  = false;
                response.Message = "Invalid CRON";

                await context.Response.WriteAsync(JsonConvert.SerializeObject(response));

                return;
            }

            var manager = new RecurringJobManager(context.Storage);

            var updatedJob = new Job(Type.GetType(job.Class).GetMethod(job.Method));

            manager.AddOrUpdate(job.Id, updatedJob, job.Cron, TimeZoneInfo.Utc, job.Queue);

            context.Response.StatusCode = (int)HttpStatusCode.OK;

            await context.Response.WriteAsync(JsonConvert.SerializeObject(response));
        }
Exemple #13
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.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

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

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

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

            var recurringJobs = new RecurringJobManager();

            RecurringJob.AddOrUpdate <Tasks>(x => x.SuccessTask(null, null), Cron.Minutely);
            //            RecurringJob.AddOrUpdate<Tasks>(x => x.FailedTask(null, null), "*/2 * * * *");
            recurringJobs.AddOrUpdate("Failed Task", Job.FromExpression <Tasks>(x => x.FailedTask(null)), "*/2 * * * *", TimeZoneInfo.Local);
        }
Exemple #14
0
        public ActionResult Index(SettingsModel model)
        {
            // Event
            SysEvent ev = new SysEvent();

            ev.Action      = Action.Settings;
            ev.Description = "Updated system settings";

            if (ModelState.IsValid)
            {
                // Check for changed settings we need to reflect here and now.
                SettingsModel settings = db.Settings.Single(x => x.Id == 1);
                if (settings.PingInterval != model.PingInterval)
                {
                    // Reset Hangfires recurring ping job.
                    var manager = new RecurringJobManager();
                    manager.AddOrUpdate("Enqueue", Job.FromExpression(() => Core.Jobs.Enqueue()), Cron.MinuteInterval(model.PingInterval));
                }

                // Save to database
                db.Settings.AddOrUpdate(model);
                db.SaveChanges();


                ev.ActionStatus = ActionStatus.OK;
                LogsController.AddEvent(ev, User.Identity.GetUserId());

                return(RedirectToAction("Index", "Home"));
            }
            ev.ActionStatus = ActionStatus.Error;
            LogsController.AddEvent(ev, User.Identity.GetUserId());
            return(View(model));
        }
        protected async Task CreateBuildEngineBuildAsync(Product product)
        {
            await ResetPreviousBuildAsync(product);

            BuildResponse buildResponse = null;

            if (SetBuildEngineEndpoint(product.Project.Organization))
            {
                buildResponse = BuildEngineApi.CreateBuild(product.WorkflowJobId);
            }
            if ((buildResponse != null) && (buildResponse.Id != 0))
            {
                product.WorkflowBuildId = buildResponse.Id;
                var productBuild = new ProductBuild
                {
                    ProductId = product.Id,
                    BuildId   = product.WorkflowBuildId
                };
                await ProductBuildRepository.CreateAsync(productBuild);

                await ProductRepository.UpdateAsync(product);

                var monitorJob = Job.FromExpression <BuildEngineBuildService>(service => service.CheckBuild(product.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(product.Id), monitorJob, "* * * * *");
            }
            else
            {
                // TODO: Send Notification
                // Throw Exception to force retry
                throw new Exception("Create build failed");
            }
        }
Exemple #16
0
        private void ScheduleJob(JobConfigDetails job)
        {
            //LogManager.Log($"Starting job: {job.Id}");
            if (string.IsNullOrEmpty(job.Cron) || string.IsNullOrEmpty(job.TypeName))
            {
                return;
            }

            try
            {
                var jobManager = new RecurringJobManager();
                jobManager.RemoveIfExists(job.Id);
                var type = Type.GetType(job.TypeName);
                if (type != null && job.Enabled)
                {
                    var jobSchedule = new Job(type, type.GetMethod("Start"));
                    jobManager.AddOrUpdate(job.Id, jobSchedule, job.Cron, TimeZoneInfo.Local);
                    //LogManager.Log($"Job {job.Id} has started");
                }
                else
                {
                    //LogManager.Log($"Job {job.Id} of type {type} is not found or job is disabled");
                }
            }
            catch (Exception ex)
            {
                //LogManager.Log($"Exception has been thrown when starting the job {ex.Message}", LogLevel.Critical);
            }
        }
Exemple #17
0
        protected override void Initialize(HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);

            var manager = new RecurringJobManager();

            manager.AddOrUpdate("CheckProductsObsolete", Job.FromExpression(() => CheckProductsObsolete()), Cron.Daily());
        }
Exemple #18
0
        public JsonResult AddJob1([FromServices] RecurringJobManager jobManager)
        {
            string id = Guid.NewGuid().ToString("N");

            jobManager.AddOrUpdate(id, () => MyJob.即時任務(null), Cron.Minutely);

            return(Json(new { success = true, id }));
        }
Exemple #19
0
        public void JobUpdate(string recurringJobId, Hangfire.Common.Job job, string interval)
        {
            var manager = new RecurringJobManager();

            //manager.RemoveIfExists("my-job-id");
            manager.AddOrUpdate(recurringJobId, job, interval);
            manager.Trigger(recurringJobId);
        }
Exemple #20
0
        public override void Initialize()
        {
            //Dependency Injection
            IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());

            IocManager.IocContainer.Register(
                Component
                .For <IAuthenticationManager>()
                .UsingFactoryMethod(() => HttpContext.Current.GetOwinContext().Authentication)
                .LifestyleTransient()
                );

            //Areas
            AreaRegistration.RegisterAllAreas();

            //Routes
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //Bundling
            BundleTable.Bundles.IgnoreList.Clear();
            CommonBundleConfig.RegisterBundles(BundleTable.Bundles);
            AppBundleConfig.RegisterBundles(BundleTable.Bundles);//SPA!
            FrontEndBundleConfig.RegisterBundles(BundleTable.Bundles);

            AppVar.DefaultConnectString = System.Configuration.ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

            // hangfire
            var manager = new RecurringJobManager();

            manager.AddOrUpdate("HangFileSchedulerLienThongTuCongBo"
                                , Job.FromExpression(() => new HangFileScheduler().HangFileSchedulerLienThongTuCongBo())
                                , Cron.MinuteInterval(5));

            manager.AddOrUpdate("HangFileSchedulerLienThongDangKyCongBo"
                                , Job.FromExpression(() => new HangFileScheduler().HangFileSchedulerLienThongDangKyCongBo())
                                , Cron.MinuteInterval(5));

            manager.AddOrUpdate("HangFileSchedulerLienThongDangKyQuangCao"
                                , Job.FromExpression(() => new HangFileScheduler().HangFileSchedulerLienThongDangKyQuangCao())
                                , Cron.MinuteInterval(5));

            manager.AddOrUpdate("HangFileSchedulerLienThongCoSoDuDieuKien"
                                , Job.FromExpression(() => new HangFileScheduler().HangFileSchedulerLienThongCoSoDuDieuKien())
                                , Cron.MinuteInterval(5));
        }
        public void Attach(Container container)
        {
            GlobalConfiguration.Configuration.UseActivator(new Activator(container));

            var jobManager = new RecurringJobManager();

            jobManager.AddOrUpdate(
                NotifyParserJob.JobId,
                Job.FromExpression((NotifyParserJob job) => job.Execute()), Cron.Daily(20));
        }
Exemple #22
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ApplicationDbContext context,
                              RoleManager <ApplicationRole> roleManager,
                              UserManager <Employee> userManager
                              )
        {
            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.UseCookiePolicy();

            app.UseAuthentication();

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

            DummyData.InitializeAsync(app);

            app.UseHangfireDashboard();
            app.UseHangfireServer();
            var manager = new RecurringJobManager();

            manager.AddOrUpdate("UPDATE-VACATION-TIME", Job.FromExpression(() => updateVacationTime()), "0 0 1 * * ", TimeZoneInfo.Local);
            manager.AddOrUpdate("UPDATE-SICK-LEAVE", Job.FromExpression(() => updateSickLeave()), "0 0 1 1 * ", TimeZoneInfo.Local);
        }
        public void Bootstrap()
        {
            var manager = new RecurringJobManager();

            foreach (var job in _recurringJobs)
            {
                var type   = job.GetType();
                var method = type.GetMethod("Work");
                var j      = new Job(type, method);

                manager.AddOrUpdate(type.Name, j, job.CronExpression());
            }
        }
        private static void AddRecurringJobs()
        {
            //LogProvider.SetCurrentLogProvider(new ColouredConsoleLogProvider());
            //RecurringJob.AddOrUpdate("ev-min-recur", () => Console.WriteLine("Recurring Background Methods"), Cron.Minutely);
            var jobManager = new RecurringJobManager(new SqlServerStorage("HangfireConnection"));
            Action <HttpContext> expression = PerformJob;
            var job = new Job(expression.Method, HttpContext.Current);

            jobManager.AddOrUpdate("recurring-job-minute",
                                   job,
                                   Cron.Minutely());
            jobManager.Trigger("recurring-job-minute");
        }
Exemple #25
0
        public void Configuration(IAppBuilder app)
        {
            GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection").UseTagsWithSql();

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

            RecurringJob.AddOrUpdate <Tasks>(x => x.SuccessTask(null, null), Cron.Minutely);

            var recurringJobs = new RecurringJobManager();

            recurringJobs.AddOrUpdate("Failed Task", Job.FromExpression <Tasks>(x => x.FailedTask(null, null)), "*/2 * * * *", TimeZoneInfo.Local);
        }
Exemple #26
0
        public ActionResult AddOrUpdate()
        {
            RecurringJob.AddOrUpdate(() => Console.Write("Powerful!"), "0 12 * */2");
            //RecurringJob.AddOrUpdate("RecurringJob", () => Console.WriteLine("Simple RecurringJob!"), "1 * * * * ");
            //每小时执行一次
            RecurringJob.AddOrUpdate("some-id", () => Console.WriteLine(), Cron.Hourly);
            //RecurringJob.RemoveIfExists("some-id");
            //RecurringJob.Trigger("some-id");
            var manager = new RecurringJobManager();

            manager.AddOrUpdate("some-id", Job.FromExpression(() => Console.WriteLine()), Cron.Yearly());
            return(Ok());
        }
Exemple #27
0
        public void Configuration(IAppBuilder app)
        {
            GlobalConfiguration.Configuration
            .UseSqlServerStorage("DefaultConnection");
            app.UseHangfireDashboard();
            app.UseHangfireServer();
            //updates codes
            var manager = new RecurringJobManager();
            var codes   = new PopulateCodes();

            manager.AddOrUpdate("Codes", Job.FromExpression(() => codes.UpdatingCodes()), Cron.Hourly()); // schedule task using hangfire
            codes.Statics();
            ConfigureAuth(app);
        }
Exemple #28
0
        public void Configuration(IAppBuilder app)
        {
            // Default
            ConfigureAuth(app);

            // SignalR
            app.MapSignalR();

            // HangFire
            GlobalConfiguration.Configuration.UseSqlServerStorage("DefaultConnection");
            app.UseHangfireDashboard();

            // Hangfire settings
            BackgroundJobServerOptions opt = new BackgroundJobServerOptions();

            opt.WorkerCount = 20;
            opt.Queues      = new[] { "critical", "default" };

            app.UseHangfireDashboard("/hangfire", new DashboardOptions
            {
                AuthorizationFilters = new[] { new MyRestrictiveAuthorizationFilter() }
            });
            app.UseHangfireServer(opt);

            // HangFire Jobs
            var manager = new RecurringJobManager();

            // Keep the cart DB cleaned once daily!
            manager.AddOrUpdate("CleanupCarts", Job.FromExpression(() => new HangFire.Jobs().CleanupCarts()), Cron.Daily(), new RecurringJobOptions {
                QueueName = "critical"
            });
            // Chnage the daily deals with 3 new random deals!
            // FYI this is set to 5 minutes for demo purposes
            manager.AddOrUpdate("DailyDeals", Job.FromExpression(() => new HangFire.Jobs().DailyDeals(3)), Cron.MinuteInterval(5), new RecurringJobOptions {
                QueueName = "default"
            });
        }
        public void Initialise()
        {
            var manager = new RecurringJobManager();

            foreach (TaskEntry task in this.Tasks.Items)
            {
                var type = Type.GetType(task.ServiceType);
                if (type != null)
                {
                    var method = type.GetMethod(task.Method);
                    var job    = new Job(type, method);

                    manager.AddOrUpdate(task.Name, job, task.Cron);
                }
            }
        }
        protected async Task CreateBuildEngineBuildAsync(Product product, Dictionary <string, object> parmsDictionary, PerformContext context)
        {
            await ResetPreviousBuildAsync(product);

            BuildResponse buildResponse = null;

            if (SetBuildEngineEndpoint(product.Project.Organization))
            {
                var targets     = GetTargets(parmsDictionary, "apk play-listing");
                var environment = GetEnvironment(parmsDictionary);
                environment["PRODUCT_ID"] = product.Id.ToString();
                environment["PROJECT_ID"] = product.ProjectId.ToString();
                var build = new Build
                {
                    Targets     = targets,
                    Environment = environment
                };
                buildResponse = BuildEngineApi.CreateBuild(product.WorkflowJobId, build);
            }
            if ((buildResponse != null) && (buildResponse.Id != 0))
            {
                product.WorkflowBuildId = buildResponse.Id;
                var productBuild = new ProductBuild
                {
                    ProductId = product.Id,
                    BuildId   = product.WorkflowBuildId
                };
                await ProductBuildRepository.CreateAsync(productBuild);

                await ProductRepository.UpdateAsync(product);

                var monitorJob = Job.FromExpression <BuildEngineBuildService>(service => service.CheckBuild(product.Id));
                RecurringJobManager.AddOrUpdate(GetHangfireToken(product.Id), monitorJob, "* * * * *");
            }
            else
            {
                var messageParms = new Dictionary <string, object>()
                {
                    { "projectName", product.Project.Name },
                    { "productName", product.ProductDefinition.Name }
                };
                await SendNotificationOnFinalRetryAsync(context, product.Project.Organization, product.Project.Owner, "buildFailedUnableToCreate", messageParms);

                // Throw Exception to force retry
                throw new Exception("Create build failed");
            }
        }