基于springboot的定时任务实现(非分布式)

1. 核心注解

在springboot项目中我们可以很方便地使用spring自己的注解@Scheduled@EnableScheduling配合来实现便捷开发定时任务。

@EnableScheduling注解的作用是发现注解@Scheduled的任务并后台执行,此注解可以加到启动类上也可以加到执行调度任务类上。

经测试,当有多个包含定时任务的类时,@EnableScheduling注解加在其中一个类上就可以保证所有定时任务的成功实现。

注意:定时任务的类上还需要配合使用@Configuration@Component注解,这两个注解都可以。

2. 实例代码:

2.1 @EnableScheduling加在启动类上;

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Component
public class TestSchedule01 {

    @Scheduled(cron = "0 * * * * ? ")
    public void test() {
        System.out.println("我是定时任务01,我执行了" + DateUtil.formatDateByDateTime(new Date()));
    }
}
import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Configuration
public class TestSchedule02 {

    @Scheduled(cron = "1 * * * * ? ")
    public void test() {
        System.out.println("我是定时任务02,我执行了" + DateUtil.formatDateByDateTime(new Date()));
    }
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class DemoApplication {

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

}

2.1 @EnableScheduling加在任务类上;

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Component
@EnableScheduling
public class TestSchedule01 {

    @Scheduled(cron = "0 * * * * ? ")
    public void test() {
        System.out.println("我是定时任务01,我执行了" + DateUtil.formatDateByDateTime(new Date()));
    }
}
import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Configuration
public class TestSchedule02 {

    @Scheduled(cron = "1 * * * * ? ")
    public void test() {
        System.out.println("我是定时任务02,我执行了" + DateUtil.formatDateByDateTime(new Date()));
    }
}

注意:只需要在其中一个任务类上加上@EnableScheduling注解,所有的定时任务就都可以正常运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值