/// <summary>
        /// 关闭任务
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="newJobStatedict">要关闭的任务</param>
        private void CloseJob(string userId, Dictionary <string, JobState> newJobStatedict)
        {
            Dictionary <string, string> dict = _cache.GetCache <Dictionary <string, string> >("__ConnectionUserCacheKey");

            if (dict.Count > 0)
            {
                foreach (KeyValuePair <string, JobState> pair in newJobStatedict)
                {
                    string jobClde = pair.Key;
                    switch (pair.Value)
                    {
                    case JobState.Open:
                        break;

                    case JobState.Closed:
                        // 关闭任务
                        QuartzUtil.DeleteJob(jobClde);
                        //向客户端广播消息
                        if (dict.ContainsKey(userId))
                        {
                            string connId = dict[userId];
                            Clients.Client(connId).BroadcastJobClosed(jobClde + "已关闭");
                        }
                        break;
                    }
                }
            }
        }
Beispiel #2
0
        public void QuartzTest(int type)
        {
            JobKey jobKey = new JobKey("demo", "group1");

            switch (type)
            {
            //添加任务
            case 1:
                var trigger = TriggerBuilder.Create()
                              .WithDescription("触发器描述")
                              .WithIdentity("test")
                              //.WithSchedule(CronScheduleBuilder.CronSchedule("0 0/30 * * * ? *").WithMisfireHandlingInstructionDoNothing())
                              .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever().WithMisfireHandlingInstructionNextWithRemainingCount())
                              .Build();
                QuartzUtil.Add(typeof(MyJob), jobKey, trigger);
                break;

            //暂停任务
            case 2:
                QuartzUtil.Stop(jobKey);
                break;

            //恢复任务
            case 3:
                QuartzUtil.Resume(jobKey);
                break;
            }
        }
        public ActionResult DeleteJob()
        {
            string jobName = "job1";

            QuartzUtil.DeleteJob(jobName);
            return(Redirect("/"));
        }
        public ActionResult Index()
        {
            string jobs = QuartzUtil.PrintAllJobsInfo().Result;

            ViewBag.AllJobs = jobs.Replace("\n", "<br />");
            return(View());
        }
Beispiel #5
0
        public void QuartzTask(int type)
        {
            JobKey jobKey = new JobKey("workTicket", "work");

            switch (type)
            {
            //添加任务
            case 1:
                var trigger = TriggerBuilder.Create()
                              .WithDescription("workTicket")
                              .WithIdentity("admin")
                              //.WithSchedule(CronScheduleBuilder.CronSchedule("0 0/30 * * * ? *").WithMisfireHandlingInstructionDoNothing())
                              .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires())
                              .Build();
                Jobs._hub = _hub;
                _         = QuartzUtil.Add(typeof(Jobs), jobKey, trigger);
                break;

            //暂停任务
            case 2:
                _ = QuartzUtil.Stop(jobKey);
                break;

            //恢复任务
            case 3:
                _ = QuartzUtil.Resume(jobKey);
                break;

            //删除任务
            case 4:
                _ = QuartzUtil.Delete(jobKey);
                break;
            }
        }
        public ActionResult AddJob()
        {
            int intervalSecs = 10;
            Dictionary <string, object> map = new Dictionary <string, object>();

            map.Add("job_data", "add the data you want to use in the job");
            QuartzUtil.AddSimpleJob <TestJob>("TEST_JOB_" + DateTime.Now.ToString("HHmmss"), intervalSecs, map);
            return(Redirect("/"));
        }
        public static void Restart()
        {
            Log.Info("Restart()  卸载所有定时器... ");
            QuartzUtil.Shutdown(false);     //true 等待当前job执行完再关闭,false 直接关闭
            Log.Info("Restart()  准备重启 ");
            HttpRuntime.UnloadAppDomain();  //会触发Application_End 事件
            Log.Info("Restart()  重启完成 ");

            //Activate();
        }
        static Scheduler()
        {
            async void Initialize()
            {
                Singleton = await new StdSchedulerFactory(QuartzUtil.BuildSchedulerProperties("GlobalSchedulerClient"))
                            .GetScheduler();
                await Singleton.Start();
            }

            Initialize();
        }
Beispiel #9
0
        public async static void Run()
        {
            try
            {
                string cronExpression = "0/1 * * * * ?";//这是指每天的9点和16点执行任务
                QuartzUtil.QuartzUtilSet();
                await QuartzUtil.AddJob <QuartzJob>("job1", cronExpression);

                Console.WriteLine("执行成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            // QuartzUtil.ExecuteByCron<QuartzJob>(cronExpression);//这是调用Cron计划方法
        }
Beispiel #10
0
        protected void Application_Start()
        {
            //应用程序启动时加载log4net设置
            XmlConfigurator.Configure();

            Log.Info("Application_Start 触发");

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            // 初始化启动定时任务引擎
            QuartzUtil.Init();

            // 启动设定的任务
            QuartzBase.Start();

            Log.Info("Application_Start 启动设定的任务");
        }
        /// <summary>
        /// 开启或者关闭任务
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="newJobStatedict"></param>
        private void OpenJob(string userId, Dictionary <string, JobState> newJobStatedict)
        {
            Dictionary <string, string> dict = _cache.GetCache <Dictionary <string, string> >("__ConnectionUserCacheKey");

            if (dict.Count > 0)
            {
                foreach (KeyValuePair <string, JobState> pair in newJobStatedict)
                {
                    string jobCode = pair.Key;
                    switch (pair.Value)
                    {
                    case JobState.Open:
                        //开启任务,操作数据,然后将数据广播给指定用户
                        //Cron表达式 :秒  分钟  小时  日的日  月  某一天的周  年
                        //每分钟执行
                        string CronTime = "0/5 * * * * ? ";
                        //附带参数
                        JobDataMap map;

                        switch (jobCode)
                        {
                        case "SysJob":
                            map = new JobDataMap {
                                { "Clients", Clients }
                            };
                            DateTimeOffset time = QuartzUtil.AddJob <SysJob>(jobCode, CronTime, map);
                            break;
                        }
                        //向客户端广播消息
                        if (dict.ContainsKey(userId))
                        {
                            string connId = dict[userId];
                            Clients.Client(connId).BroadcastJobOpened(jobCode + "已开启");
                        }
                        break;

                    case JobState.Closed:
                        break;
                    }
                }
            }
        }
        public void QuartzTask(string type, string jobName, string jobGroup)
        {
            JobKey jobKey = new JobKey(jobName, jobGroup);

            switch (type)
            {
            //添加任务
            case "add":
                //创建触发器(也叫时间策略)
                var trigger = TriggerBuilder.Create()
                              .WithDescription("workTicket")
                              .WithIdentity("admin")
                              //.WithSchedule(CronScheduleBuilder.CronSchedule("0 0/30 * * * ? *").WithMisfireHandlingInstructionDoNothing())
                              // 间隔固定时间执行
                              //.WithSimpleSchedule(x => x.WithIntervalInSeconds(1).RepeatForever().WithMisfireHandlingInstructionIgnoreMisfires())
                              // 只执行一次
                              .WithSimpleSchedule(x => x.WithIntervalInSeconds(1).WithRepeatCount(0).WithMisfireHandlingInstructionIgnoreMisfires())
                              .Build();
                switch (jobName)
                {
                case "AutoOperWorkTicket":
                    //实例化Jobs用到的对象(singalr)
                    AutoOperWorkTicketJobs._hub = _hub;
                    //实例化Jobs用到的对象JobService
                    AutoOperWorkTicketJobs.jobService = new JobService(_configuration);
                    _ = QuartzUtil.Add(typeof(AutoOperWorkTicketJobs), jobKey, trigger);
                    break;

                case "AutoOperQrCode":
                    //实例化Jobs用到的对象(singalr)
                    AutoOperQrCodeJobs._hub = _hub;
                    //实例化Jobs用到的对象JobService
                    AutoOperQrCodeJobs.jobService = new JobService(_configuration);
                    _ = QuartzUtil.Add(typeof(AutoOperQrCodeJobs), jobKey, trigger);
                    break;

                case "AutoRemindToWork":
                    //实例化Jobs用到的对象(singalr)
                    AutoRemindToWorkJobs._hub = _hub;
                    //实例化Jobs用到的对象JobService
                    AutoRemindToWorkJobs.jobService = new JobService(_configuration);
                    _ = QuartzUtil.Add(typeof(AutoRemindToWorkJobs), jobKey, trigger);
                    break;
                }

                break;

            //暂停任务
            case "stop":
                _ = QuartzUtil.Stop(jobKey);
                break;

            //恢复任务
            case "resume":
                _ = QuartzUtil.Resume(jobKey);
                break;

            //删除任务
            case "delete":
                _ = QuartzUtil.Delete(jobKey);
                break;
            }
        }
Beispiel #13
0
        private async Task StartPk10(Pk10Rule rule)
        {
            var prefix = $"{LotteryType.Pk10}_{rule}";

            //大管家Job,负责创建每期的扫水Job
            var stewardJob = QuartzUtil.CreateSimpleJob($"{prefix}_Steward_Job", $"{LotteryType.Pk10}_JobGroup",
                                                        Scan);

            /*
             * 北京赛车时间为每天9:00到23:50,每5分钟开一期,共179期 (北京时间)
             *
             * “0 1/5 9-23 * * ?”
             * 每天9点到23点,每5分钟的第1分钟第0秒。如 9:01:00,9:06:00 ... 9:56:00 ... 23:51:00,23:56:00
             *
             * 9-23(GMT+08:00)  =>  1-15(UTC)
             */

            var pk10Trigger = QuartzUtil.CreateTrigger(prefix, "JinMaTrigger",
                                                       $"0 1/5 {1.ToLocalHour()}-{15.ToLocalHour()} * * ?");


            //启动定时扫水
            await QuartzUtil.GetScheduler().ScheduleJob(stewardJob, pk10Trigger);


            async void Scan()
            {
                var timestamp = DateTime.UtcNow;
                var periodNo  = Pk10Scheduler.Instance.GetPeriodNo(timestamp);
                var locked    = new RulePeriodLocked(rule, periodNo);

                var jobTrigger = $"{prefix}_Scan_{periodNo}".ToJobTrigger();
                var trigger    = QuartzUtil.CreateTrigger(jobTrigger.Trigger, "0/5 * * * * ? *");
                var job        = QuartzUtil.CreateSimpleJob(jobTrigger.Job, () =>
                {
                    //避免第一轮任务执行未完成时第二轮任务开始执行,锁定 同一种玩法同一期 任务
                    lock (locked)
                    {
                        //Job废弃
                        if (locked.Finished)
                        {
                            return;
                        }

                        //超时自毁
                        if ((DateTime.UtcNow - timestamp).TotalMinutes > 5)
                        {
                            QuartzUtil.TryDestroyJob(jobTrigger).Wait();
                            locked.Finish();
                            return;
                        }

                        //扫水
                        var task = JinMaAnalyzer.Instance.GetForecastData(LotteryType.Pk10, (int)rule);
                        task.Wait();
                        var plans = task.Result;

                        /*
                         * 如果目标网站接口正常,每次都可以扫到结果,即使没有更新最新期预测数据。所以如果没有扫水结果,说明目标网站接口出错或扫到到数据异常
                         */
                        if (plans == null)
                        {
                            DataCollectedError?.Invoke(this, new CollectErrorEventArgs(rule, "扫水异常或数据数据错误"));
                            return;
                        }

                        //扫到老数据
                        if (plans.Any(p => p.LastDrawnPeriod + 1 < periodNo))
                        {
                            return;
                        }

                        //成功扫到最新数据
                        JinMaAnalyzer.Instance.CalcuteScore(plans);
                        DataCollectedSuccess?.Invoke(this,
                                                     new DataCollectedEventArgs(LotteryType.Pk10, rule, plans));

                        //扫水成功自毁
                        QuartzUtil.TryDestroyJob(jobTrigger).Wait();
                        locked.Finish();
                    }
                });

                await QuartzUtil.GetScheduler().ScheduleJob(job, trigger);
            }
        }