WebAPI接口添加定时服务
背景:
在开发小程序的API服务的时候,由于access_token的有效期为7200秒,也就是2小时,这就需要后端定时的去更新这个access_token,便于调用小程序的一些接口。
设计思路与实现步骤:
1.准备把access_token存在数据库中,如前端需要调小程序接口,通过我的后端去调小程序公开的接口。
2.我的webapi部署在IIS上,所以在Global.asax启动站点的时候,在Application_Start方法下添加我的定时任务。如下图

3.RunScheduler方法内Quartz.Net来创建任务调度器、创建作业和触发器等。
在VS中用NuGet管理器下载Quartz.Net并添加到指定的项目中去
AccessTokenJobSchedule.RunScheduler()代码如下:
public class AccessTokenJobSchedule { public static async Task RunScheduler() { // 创建作业调度器 ISchedulerFactory factory = new StdSchedulerFactory(); IScheduler scheduler = await factory.GetScheduler(); // 启动调度器 await scheduler.Start(); // 创建作业 IJobDetail job = JobBuilder.Create<UpdateAccessTokenJob>() .WithIdentity("job1", "group1") .Build(); // 创建触发器,每60min执行一次 ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInMinutes(60) .RepeatForever()) .Build(); // 加入到作业调度器中 await scheduler.ScheduleJob(job, trigger); } }
上述代码中创建作业job中,UpdateAccessTokenJob类需要继承Quzrtz中的接口IJob,实现接口IJob中的方法Execute,在Execute方法中可以编写具体的方法,即需要定时去执行的操作。
IJobDetail job = JobBuilder.Create<UpdateAccessTokenJob>().WithIdentity("job1", "group1").Build();
UpdateAccessTokenJob类代码如下
public class UpdateAccessTokenJob:IJob { public async Task Execute(IJobExecutionContext context) { //自己实现要定时执行的操作方法 db_cohccardEntities db = new db_cohccardEntities(); News news = db.News.Where(u => u.Sys_CoID == 33).FirstOrDefault(); News news2 = db.News.Where(u => u.Sys_CoID == 36).FirstOrDefault(); WeiXin weixin = new WeiXin(); string corpid = ConfigurationManager.AppSettings["corpid"]; string corpsecret = ConfigurationManager.AppSettings["corpsecret"]; Uri uri = new Uri(string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", corpid, corpsecret)); WeiXin weixin2 = new WeiXin(); string appid = ConfigurationManager.AppSettings["AppId"]; string secret = ConfigurationManager.AppSettings["AppSecret"]; Uri uri2 = new Uri(string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", appid, secret)); await Task.Run(() => { string result = weixin.GetMethod(uri); weixin = JsonConvert.DeserializeObject<WeiXin>(result); if (weixin.errcode == 0) { news.Sys_CoID = 33; news.NewsState = 1; news.NewsContent = weixin.access_token; news.NewsAddTime = DateTime.Now; db.SaveChanges(); } string result2 = weixin2.GetMethod(uri2); weixin2 = JsonConvert.DeserializeObject<WeiXin>(result2); if (weixin2.errcode == 0) { news2.Sys_CoID = 36; news2.NewsState = 1; news2.NewsContent = weixin2.access_token; news2.NewsAddTime = DateTime.Now; db.SaveChanges(); } }); } }
iis配置你使用到的程序池配置,在程序池的高级设置中:
启动模式:AlwaysRunning
固定时间间隔(分钟):0
闲置超时(分钟):0


浙公网安备 33010602011771号