SpringBoot定时任务

1.定时任务的作用:

 定时任务相当于一个闹钟,在规定的时间内执行什么命令或者脚本 

2.Cron表达式

Cron表达式由6~7项组成,中间用空格分开。从左到右依次是: 秒、分、时、日、月、周几、年(可省略)

Cron表达式的值可以是数字,也可以是以下符号:

"*":所有值都匹配

"?":无所谓,不关心,通常放在“周几”里

",":或者

"/":增量值

"-":区间

例如:

0 * * * * ?:每分钟(当秒为0的时候)
0 0 * * * ?:每小时(当秒和分都为0的时候)
0/5 * * * * ?:每5秒
0 5/15 * * * ?:每小时的5分、20分、35分、50分
0 0 9,13 * * ?:每天的9点和13点
0 0 8-10 * * ?:每天的8点、9点、10点
0 0/30 8-10 * * ?:每天的8点、8点半、9点、9点半、10点
0 0 9-17 * * MON-FRI :每周一到周五的9点、10点…直到17点(含)
0 0 0 25 12 ? :每年12月25日圣诞节的0点0分0秒(午夜)
0 30 10 * * ? 2016:2016年每天的10点半

 代码实例:

maven导入的包:

<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
       <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.1.RELEASE</version> </dependency>

applicationContext.xml 配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/task
       http://www.springframework.org/schema/task/spring-task.xsd">

    <context:component-scan base-package="edu.demo.task"/>

    <!-- 启用定时任务的注解驱动 -->
    <task:annotation-driven/>

</beans>

编写测试类:

 @Test
    public void testTask() throws InterruptedException {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //DemoTaskService service = context.getBean("taskService", DemoTaskService.class);
        Thread.sleep(5000000);
    }

 SpringBoot使用定时任务,在启动类加上注解@EnableScheduling

@SpringBootApplication
@MapperScan("com.ywb.csms.mps.dao")
@Controller
@EnableTransactionManagement
@EnableAsync(proxyTargetClass=true)
@EnableScheduling
public class MpsApplication{

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(MpsApplication.class, args);

    }
}

每天晚上12执行定时任务

@Component
public class TimerTask {

    @Autowired
    private TicketService ticketService;

    /**
     * 每天晚上0点,工单处理完成24小时后,极光推送消息
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void scheduledTask(){
        ticketService.listTicketByFinished();
    }
}



 

 

 

原文地址:https://www.cnblogs.com/ywbmaster/p/10011684.html