java定时任务 quartz结合spring

导入依赖


org.quartz-scheduler
quartz
2.3.0


org.quartz-scheduler
quartz-jobs
2.3.0



org.springframework
spring-context-support
5.0.2.RELEASE


org.springframework
spring-core
5.0.8.RELEASE


org.springframework
spring-tx
5.0.2.RELEASE

配置文件配置定时任务

自定义要定时执行的方法

import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class MyJob {

private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public void abc(){
System.out.println(Thread.currentThread()+ ":" + sdf.format(new Date()));
}
}

spring配置加载任务



<context:component-scan base-package="com.demo.job"/>

























加载spring启动定时任务

public class JobApplication {
public static void main(String[] args) throws IOException {
new ClassPathXmlApplicationContext("classpath:applicationContext-jobs.xml");
// 阻塞
System.in.read();
}
}

注解配置间隔任务

自定义任务类,需要执行的方法使用@Scheduled注解修饰

@Component
public class MyJob2 {

private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

/**
* initialDelay: 启动时延迟多少毫秒后才执行
* fixedDelay: 每间隔多长时间执行
*/
@Scheduled(initialDelay = 1000,fixedDelay = 2000)
//@Scheduled(cron = "0/2 * * * * ?")
public void tt(){
System.out.println("job2:" + sdf.format(new Date()));
}
}

spring配置加载任务



<context:component-scan base-package="com.demo.job"/>

task:annotation-driven/


posted @ 2021-01-08 17:18  笨蛋树上笨蛋果  阅读(105)  评论(0)    收藏  举报