在 SpringBoot 中使用 @EnableScheduling、@Scheduled 轻松实现定时任务

前言

之前接手师兄的 ITAEMBook 项目,里边就有类似王荣耀的 王者战报 功能,定期推送阅读信息给用户
现在实现定时任务的方法,很多人使用的是 quartz,而 SpringBoot 自带的两个注解就可以轻松搞定

定时任务

1、效果

这里写图片描述

2、代码
① 在 main 中开启定时任务的注解 @EnableScheduling

package com.cun;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling   //开启定时任务注解
@SpringBootApplication
public class AsMailTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsMailTaskApplication.class, args);
    }
}

②在 Service 中编写定时任务 @Scheduled

package com.cun.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class TaskService {

    /**
     * second(秒), minute(分), hour(时), day of month(日), month(月), day of week(周几).
     * 例子:
     *  【0 0/5 14,18 * * ?】 每天14点整,和18点整,每隔5分钟执行一次
     *  【0 15 10 ? * 1-6】 每个月的周一至周六10:15分执行一次
     *  【0 0 2 ? * 6L】每个月的最后一个周六凌晨2点执行一次
     *  【0 0 2 LW * ?】每个月的最后一个工作日凌晨2点执行一次
     *  【0 0 2-4 ? * 1#1】每个月的第一个周一凌晨2点到4点期间,每个整点都执行一次;
     */
    @Scheduled(cron = "0,1,2,3,4 * * * * MON-SAT")
    public void runTask(){
        System.out.println(new Date()+"发布王者战报");
    }
}

③ Maven 依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

猜你喜欢

转载自blog.csdn.net/larger5/article/details/80534583