热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

springboot实现简单的定时任务?

1.pom.xml所需依赖pom.xmlorg.springframework.boot

 1.pom.xml所需依赖

pom.xmlorg.springframework.bootspring-boot-starter-securityorg.springframework.bootspring-boot-starter-quartz

 2.定时任务作用那块?

package org.asyware.expressway.quartz;import org.asyware.expressway.service.UserService;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;import lombok.extern.slf4j.Slf4j;@DisallowConcurrentExecution
@Slf4j
public class ToolQuartz extends QuartzJobBean{@Autowiredprivate UserService userService;@Overrideprotected void executeInternal(JobExecutionContext context) throws JobExecutionException {log.debug("定时任务启动");try {//定时调用的方法userService.deleteUserinfo(1);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

package org.asyware.expressway.config;import org.asyware.expressway.quartz.ToolQuartz;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class QuartzConfig {@Beanpublic JobDetail uploadTaskDetail() {return JobBuilder.newJob(ToolQuartz.class).withIdentity("ToolQuartz").storeDurably().build();}@Beanpublic Trigger uploadTaskTrigger() {CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("0/5 * * * * ?");return TriggerBuilder.newTrigger().forJob(uploadTaskDetail()).withIdentity("ToolQuartz").withSchedule(scheduleBuilder).build();}}

3.启动类  没有添加@EnableScheduling注解也可以,具体原因还没了解

package org.asyware.expressway;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@SpringBootApplication
//@EnableAsync
//@EnableScheduling
@MapperScan("org.asyware.expressway.mapper") // 启动时扫描的mapper
@RestControllerpublic class ExpresswayApplication {public static void main(String[] args) {SpringApplication.run(ExpresswayApplication.class, args);}@GetMapping("/test")public String test() {return "ok";}}

就很简单的这几步,就可以了。


推荐阅读
author-avatar
accosta谭_738
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有