using Common.Model; using Common.Wechat; using CoreEntity.BAL; using CoreEntity.DAL; using CoreEntity.Entity; using CoreEntity.TimeJob; using JCSoft.WX.Framework.Api; using Pomelo.AspNetCore.TimedJob; using Quartz; using Quartz.Impl; using Quartz.Impl.Matchers; using Quartz.Impl.Triggers; using Quartz.Spi; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; using ZcPeng.PublicLibrary; using ZcPeng.weixin.PublicAccount; namespace CoreEntity.TimedTask { public class AutoSupplyGapPushJob : Job { private IApiClient _client; public AutoSupplyGapPushJob(IApiClient client) { _client = client; } // Begin 起始时间;Interval执行时间间隔,单位是毫秒,建议使用以下格式,此处为3小时; //SkipWhileExecuting是否等待上一个执行完成,true为等待; [Invoke(Begin = "2018-12-17 17:16", Interval = 1000 * 60 * 1 * 1, SkipWhileExecuting = true)] public void Run() { //Job要执行的逻辑代码 //LogHelper.Info("Start crawling"); //AddToLatestMovieList(100); //AddToHotMovieList(); //LogHelper.Info("Finish crawling"); //DataAccess WechatHelper.getAccessToken(_client); } } public class PushJob : IJob { //private IApiClient _client; public PushJob() { // _client = new DefaultApiClient(); } public Task Execute(IJobExecutionContext context) { /*//获取推送上下限 IList pushLimits = PushRecordDAL.GetPushLimit(); JobDataMap dataMap = context.JobDetail.JobDataMap; string LoginAccountId = dataMap.GetString("LoginAccountId"); string RoleId = dataMap.GetString("RoleId"); string StaffDocId = StaffDocDAL.GetStaffId(LoginAccountId); //获取待推送账户:上次供货业务员,取最低价格的业务员 string filterstr = " and UserId IS NOT NULL and UserId !='' " // +" and FocusMicNo IS NOT NULL and FocusMicNo !='' " + ((RoleId == "1" || RoleId == "6" || RoleId == "7") ? "" : (" and SaleManId = '" + StaffDocId + "' ")) //只查询当前采购员的联系人 ; Dictionary gapnum; List GetPushContacts = ContactBAL.GetPushContactWithGoods(filterstr,"", pushLimits, out gapnum); //判断参数是否合法 if (GetPushContacts.Count == 0) { return Console.Out.WriteLineAsync("Greetings from HelloJob!" + "没有建立账户,或者业务员没有绑定"); } //添加推送记录并推送 var result = PushBAL.pushAll(GetPushContacts, gapnum, LoginAccountId, null); var codeids = result[result.Count - 1]; Object Ids; codeids.TryGetValue("Ids", out Ids); List ids = (List)Ids; foreach (String recordId in ids) { CancelPushRecordTimedJob.CancelPushRecord(recordId, DateTime.Now, CancelPushRecordTimedJob.HoursToCancel); } */ JobDataMap dataMap = context.JobDetail.JobDataMap; string LoginAccountId = dataMap.GetString("LoginAccountId"); string RoleId = dataMap.GetString("RoleId"); string FilterLimit = dataMap.GetString("FilterLimit"); string FilterCont = dataMap.GetString("FilterCont"); bool success = PushBAL.Push(LoginAccountId,RoleId, FilterLimit, FilterCont,out var result); //foreach (PushContactWithGoods contact in GetPushContacts) //{ // int StoreGapNum = 0; // if (gapnum.ContainsKey(contact.GoodsId)) // { // PushStorLimit limit; // gapnum.TryGetValue(contact.GoodsId, out limit); // StoreGapNum = Convert.ToInt32(limit.StoreGapNum); // } // string PushAccountId = contact.UserId; // DateTime EndTime = DateTime.Now.AddHours((double)24); // string LoginAccountId = "1"; // //新建推送记录 // var success = PushBAL.BatchPush(null, null, // contact.UserId, contact.GoodsId, contact.GoodsCode // , contact.GoodsName, StoreGapNum // , contact.GoodsSpec, contact.Manufacturer // , contact.BusinessId, contact.BusinessCode, contact.BusinessName // , contact.SuppliersId, contact.BrandName, contact.BrandId // , StoreGapNum, contact.LastPrice // , contact.EntId, contact.Remark // , LoginAccountId // , _client); // // Message msg = TimeTask.sendSupplyMassMesage(_client, Convert.ToInt32(PushAccountId), // // contact.GoodsName, // // contact.StoreGapNum, // // contact.GoodsSpec, // // contact.BrandName, // // contact.LastPrice, // // EndTime); // // PushRecordDAL.AddOrUpdatePushRecord(Convert.ToInt32(PushAccountId), contact.GoodsId, contact.GoodsCode//PushAccountId // //, contact.GoodsName, contact.StoreGapNum, // //contact.GoodsSpec,contact.Manufacturer, // //contact.BusinessId,contact.BusinessCode,contact.BusinessName // //, contact.SuppliersId, // //contact.BrandName, contact.BrandId // //, "","","", "", contact.LastPrice, contact.StoreGapNum);//entid remark feedbackid confirmperson //} return Console.Out.WriteLineAsync("Greetings from PushJob!:"+ result); } } //public class JobFactoryMy : IJobFactory //{ // private readonly IContainer _container; // public JobFactoryMy(IContainer container) // { // _container = container; // } // public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) // { // return (IJob)_container.Resolve(bundle.JobDetail.JobType); // } // public void ReturnJob(IJob job) // { // throw new NotImplementedException(); // } //} class MyServiceJobFactory : IJobFactory { protected readonly IServiceProvider _container; public MyServiceJobFactory(IServiceProvider container) { _container = container; } public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) { return _container.GetService(bundle.JobDetail.JobType) as IJob; } public void ReturnJob(IJob job) { } } public class TimedProgram { public static async Task RunProgram(string second , string minute, string hour,string RoleId,string LoginAccountId,string FilterLimit,string FilterCont, IApiClient _client) { #region 获取推送时间 DataTable dt = new DataTable(); string result; if (second == null || minute == null || hour == null) { List parameters1 = new List(); bool success = DataAccess.GetValues("select hour,minute,second from " + Config.TablePrefix + "TimeTask where Id=1", ref dt, parameters1.ToArray(), out result); // 把DataTable转换为IList IList timets = new List(); if (dt!=null && dt.Rows.Count > 0) { // 把DataTable转换为IList timets = ModelConvertHelper.ConvertToModel(dt); TimeTask first = (TimeTask)timets.First(); hour = first.Hour; minute = first.Minute; second = first.Second; } } if (hour == null || hour.Length == 0 || minute == null || minute.Length == 0 || second == null || second.Length == 0) { await Console.Error.WriteLineAsync("参数错误"); } #endregion try { // Grab the Scheduler instance from the Factory NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", "binary" } }; StdSchedulerFactory factory = new StdSchedulerFactory(props); IScheduler scheduler = await factory.GetScheduler(); // 启动任务调度器 await scheduler.Start(); // 定义一个 Job string key = "job_" + LoginAccountId + "_" + FilterLimit.Replace(" and GoodsId in ('", "").Replace("','", "-").Replace("') ", "") + "_" + FilterCont.Replace(" and GoodsId in ('", "").Replace(" and ContactId in ('", "").Replace("','", "-").Replace("') ", ""); IJobDetail job = JobBuilder.Create() .WithIdentity(key, "group1") .UsingJobData("LoginAccountId", LoginAccountId) .UsingJobData("RoleId", RoleId) .UsingJobData("FilterLimit", FilterLimit) .UsingJobData("FilterCont", FilterCont) .Build(); //ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() // .WithIdentity("trigger1") // 给任务一个名字 // .StartAt(DateTime.Now) // 设置任务开始时间 // .ForJob("job1", "group1") //给任务指定一个分组 // .WithSimpleSchedule(x => x // .WithIntervalInSeconds(30) //循环的时间 1秒1次 // .RepeatForever()) // .Build(); //每天9:30:00执行 CronTriggerImpl trigger = (CronTriggerImpl)TriggerBuilder.Create() .WithIdentity("trigger1") // 给任务一个名字 .StartAt(DateTime.Now) // 设置任务开始时间 .ForJob(key, "group1") //给任务指定一个分组 :每个业务员,每一次推送一个key .WithCronSchedule(second + " "+ minute + " " +hour+ " * * ?") .Build(); GroupMatcher groupMatcher = GroupMatcher.GroupEquals("group1"); IReadOnlyCollection set = await scheduler.GetJobKeys(groupMatcher); if (set.Count > 0) { foreach (JobKey jobKey in set) { if(jobKey.Name == key) { bool delsuccess = await scheduler.DeleteJob(jobKey); } } } // 等待执行任务 await scheduler.ScheduleJob(job, trigger); // some sleep to show what's happening //await Task.Delay(TimeSpan.FromMilliseconds(2000)); } catch (SchedulerException se) { await Console.Error.WriteLineAsync(se.ToString()); } } } }