Springboot实战第六天:(1)spring的计划任务ScheduledTask应用-2019-8-22

由于有一天是没有更新博客,导致在博客的书写日期上面是一直晚一天的。

今天主要实战的一些知识储备罗列--计划任务ScheduledTask

今天的定时任务是昨天的Spring  aop应用的实际应用,废话不多说,上代码:

1,创建配置类,启动注解的支持

package com.amarsoft.springboot.taskscheduler;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

@Configuration
@ComponentScan("com.amarsoft.springboot.taskscheduler")
@EnableScheduling
public class TaskScheduledConfig {

}

2,创建计划任务执行类

package com.amarsoft.springboot.taskscheduler;

import java.text.SimpleDateFormat;
import java.util.Date;

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

@Service
public class ScheduledTaskService {
	private static final SimpleDateFormat  dateFormat=new SimpleDateFormat("HH:mm:ss");
	@Scheduled(fixedRate=5000)
	public void reportCurrentTime(){
		System.out.println("每个五秒执行一次"+dateFormat.format(new Date()));
	}
	@Scheduled(cron="0  29  0  ?  *  *" )
	public void fixTime(){
		System.out.println("在指定的时间内"+dateFormat.format(new Date())+"执行任务");
		
	}
	
	
}

代码解释:>1.通过@Scheduled声明该方法是计划任务,使用fixedRate属性每个固定时间执行,单位是毫秒

                  >2.使用cron属性可按照指定时间执行,此处是写的每天的00:29:00执行,cron是unix和类unix系统下的定时任务

注意cron的配置: cron是设置定时执行的表达式

       @Scheduled(cron="0  29  0  ?  *  *" )表示每天的00:29:00执行一次

       @Scheduled(cron="0 0/5 * * * ?" )表示每隔五分钟执行一次

       zone表示执行时间的时区

       FixedDelay 和fixedDelayString 表示一个固定延迟时间执行,上个任务完成后,延迟多长时间执行

        fixedRate 和fixedRateString表示一个固定频率执行,上个任务开始后,多长时间后开始执行

        initialDelay 和initialDelayString表示一个初始延迟时间,第一次被调用前延迟的时间

3,测试运行

package com.amarsoft.springboot.taskscheduler;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TaskScheduledApplication {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(TaskScheduledConfig.class);

	}
}

4,执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值