前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >@Scheduled 注解的使用

@Scheduled 注解的使用

作者头像
yawn
发布2018-03-14 11:39:15
7670
发布2018-03-14 11:39:15
举报

1.启用定时任务(@EnableScheduling)

代码语言:javascript
复制
package com.example.demo;

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

@SpringBootApplication
@EnableScheduling
public class DemoApplication {

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

2.使用@Scheduled

代码语言:javascript
复制
package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
 * Created by yawn on 2017-07-13.
 */

@Configuration
public class TaskTest {

    TaskTest(){
        System.out.println("construct =======>>>>>>>>>>>");
    }

    // fixedDelay 和 fixedDelayString 马上开始执行任务
    @Scheduled(fixedDelay = 1000)
    public void task() {
        System.out.println("1>>>>>>>>===========");
    }
    @Scheduled(fixedDelayString = "2000")
    public void task4() {
        System.out.println("4===========>>>>>>>>");
    }




    // 延迟后执行任务
    @Scheduled(initialDelay = 5000, fixedRate = 1000)
    public void task1() {
        System.out.println("2===========>>>>>>>>");
    }

    @Scheduled(initialDelayString = "5000", fixedRateString = "1000")
    public void task3() {
        System.out.println("3===========>>>>>>>>");
    }


    /**
     * cron: A cron-like expression, extending the usual UN*X definition to include
     * triggers on the second as well as minute, hour, day of month, month
     * and day of week.  e.g. {@code "0 * * * * MON-FRI"} means once per minute on
     * weekdays (at the top of the minute - the 0th second).
     *
     * 这里表达式只有六位,写成七位就会报错
     * 此六位分别表示      秒、分钟、小时、日、月、星期(没有年)
     */
    @Scheduled(cron = "3,13,23,33 * * * * ?")
    public void task2() {
        System.out.println(new Date(System.currentTimeMillis()));
    }
}

最后一个方法的执行结果如下:

?

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档