springboot2.0 快速使用定时任务开发介绍

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ljk126wy/article/details/83079070

1 springboot 默认的定时任务处理

查看官方文档:http://spring.io/guides/gs/scheduling-tasks/ 我们这里将根据官方文档进行讲解如何使用。

demo工具和版本说明:

开发工具:Spring Tool Suite (STS)

jdk版本:1.8.0_144

springboot版本:2.0.5.RELEASE

使用spirngboot自带的任务调度拢共需要2步

1 启动类上声明 @EnableScheduling

2 spring bean 方法上声明 @Scheduled 并在注解中指定启动的规则

直接上代码

package cn.lijunkui;

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

@SpringBootApplication
@EnableScheduling
public class SpringbootlearnApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringbootlearnApplication.class, args);
	}
}
package cn.lijunkui.task.own;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
 * http://www.bejson.com/othertools/cron/
 * @author lijunkui
 *
 */
@Component
public class SchedulerTask {
	
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	//固定的时间执行 也就是 5秒执行一次
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTimeFixedRate() {
        log.info("reportCurrentTimeFixedRate The time is now {}", dateFormat.format(new Date()));
    }
}

测试效果

接下俩我们重点说一下 Scheduled 注解 的经常使用参数设置项

fixedRate :固定的时间执行 也就是 多少秒执行一次。 这个我们上面的代码已经介绍完毕。

fixedDelay:执行完毕后再过5秒后执行

initialDelay:启动后延迟多少秒后执行 不能单独使用。

接下俩看看fixedDelay 和 initialDelay 设置项的demo案例:

package cn.lijunkui;

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

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

import cn.lijunkui.task.own.SchedulerTask;

@SpringBootApplication
@EnableScheduling
public class SpringbootlearnApplication {
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); 
	public static void main(String[] args) {
		SpringApplication.run(SpringbootlearnApplication.class, args);
		 log.info("reportCurrentTimeInitialDelay fixedRate The time is start {}", dateFormat.format(new Date()));
	}
}
package cn.lijunkui.task.own;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
 * http://www.bejson.com/othertools/cron/
 * @author jrrry
 *
 */
@Component
public class SchedulerTask {
	
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

 
	//执行完毕后再过5秒后执行
    @Scheduled(fixedRate= 5000)
    public void reportCurrentTimeFixedDelay() {
        log.info("reportCurrentTimeFixedDelay The time is now {}", dateFormat.format(new Date()));
    }
    //延迟1秒后执行 然后每5秒执行一次
    @Scheduled(initialDelay=1000, fixedRate=5000)
    public void reportCurrentTimeInitialDelay() {
        log.info("reportCurrentTimeInitialDelay fixedRate The time is now {}", dateFormat.format(new Date()));
    }
	
}

测试结果:

同时 Scheduled 还支持 Cron 表达式方式

package cn.lijunkui.task.own;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class SchedulerTaskForCron {
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	/**
	 * 每天的14:00 执行一次
	 */
	@Scheduled(cron="0 0 14 * * ?")
	private void cron() {
		 log.info("cron The time is now {}", dateFormat.format(new Date()));
	}
	
	/**
	 * 每秒执行一次
	 */
	@Scheduled(cron="* * * * * ?")
	private void cron2() {
		log.info("cron2 The time is now {}", dateFormat.format(new Date()));
	}
}

测试结果:

关于cron使用规则 网上有很多在线生成工具 例如:http://www.bejson.com/othertools/cron/

2 springboot 使用JDK 定时任务处理

2.1 Timer 

package cn.lijunkui.task.jdk;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.lijunkui.task.own.SchedulerTask;

public class DemoTask extends TimerTask{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Override
	public void run() {
		 log.info("DemoTask The time is now {}", dateFormat.format(new Date()));
	}

}
package cn.lijunkui.task.jdk;

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

public class TimerTest {
	
	private DemoTask demoTask;
	
	public TimerTest(DemoTask demoTask) {
		this.demoTask = demoTask;
	}
	public void run() throws ParseException {
		Timer timer = new Timer();
		long delay = 0;
		long intevalPeriod = 1 * 1000;
		//timer.scheduleAtFixedRate(demoTask, delay, intevalPeriod);//每秒执行一次
		//timer.scheduleAtFixedRate(demoTask, 1000, intevalPeriod);//延迟一秒后每秒执行一次
		String datetimeStr = "2018-10-16 15:00:00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date firstTime = sdf.parse(datetimeStr);
		timer.schedule(demoTask, firstTime, intevalPeriod);//3点后开始执行 每秒执行一次
	}
}
package cn.lijunkui.task.jdk;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value = 1)
public class DemoTaskRunner implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		TimerTest test = new TimerTest(new DemoTask());
		test.run();
	}
}

2.2  ScheduledExecutorService

Java SE5 java.util.concurrent里 ScheduledExecutorService 提供了新的任务调度的方式。他是采用线程池的方式来执行的,相对于 Timer 语法更为简单。  
 

package cn.lijunkui.task.jdk.scheduledExecutorService;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.lijunkui.task.own.SchedulerTask;

public class ScheduledExecutorTask implements Runnable{
	private static final Logger log = LoggerFactory.getLogger(SchedulerTask.class);
	private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	@Override
	public void run() {
		 log.info("scheduledExecutorTask The time is now {}", dateFormat.format(new Date()));
	}
}
package cn.lijunkui.task.jdk.scheduledExecutorService;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduledExecutorTest {
	private ScheduledExecutorTask task;
	public ScheduledExecutorTest(ScheduledExecutorTask task) {
		this.task = task;
	}
	public void run() {
		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();  
	    service.scheduleAtFixedRate(task, 0, 1, TimeUnit.SECONDS);  
	}
}
package cn.lijunkui.task.jdk.timer;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import cn.lijunkui.task.jdk.scheduledExecutorService.ScheduledExecutorTask;
import cn.lijunkui.task.jdk.scheduledExecutorService.ScheduledExecutorTest;
@Component
@Order(value = 1)
public class DemoTaskRunner implements ApplicationRunner{

	@Override
	public void run(ApplicationArguments args) throws Exception {
		//TimerTest test = new TimerTest(new DemoTask());
		//test.run();
		ScheduledExecutorTest test = new ScheduledExecutorTest(new ScheduledExecutorTask());
		test.run();
	}
}

测试结果:

3 springboot 集成 quartz

springboot 2.0 已经有了quartz 的start依赖,我们可以直接引入quartz 的start依赖 来使用quartz 了。

首先我们先引入quartz start依赖

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

定义quartz 的job

package cn.lijunkui.task.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class MyJob extends QuartzJobBean{
	
	 @Autowired
	 private HelloService  helloService;
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		System.out.println("hello,job name"+name+"age:"+age);
		helloService.print();
	}
}

 创建quartz 的Config 同时定义 JobDetail 和 触发器 Trigger

package cn.lijunkui.task.quartz;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyJobConfig {
	@Bean
	public JobDetail myJobDetail() {
		return JobBuilder.newJob(MyJob.class).withIdentity("myJob").storeDurably()
				 	.usingJobData("name","lijunkui")
	                .usingJobData("age",180)
	                .build();
	}
	@Bean
	public Trigger myJobTrigger() {
		//定义具体什么执行时间.  设置一个每3秒执行一次的计划表.
		SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever();
		//定义触发器.
		return TriggerBuilder.newTrigger().forJob(myJobDetail()).withIdentity("myJobTrigger").withSchedule(simpleScheduleBuilder).build();
	}
}

定义注入的Job的Service 

package cn.lijunkui.task.quartz;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
	 public void print(){
	     System.out.println("print");
	 }
}

测试日志:

 

参考文献:https://blog.csdn.net/weixin_38492276/article/details/81146675

猜你喜欢

转载自blog.csdn.net/ljk126wy/article/details/83079070