java定时任务 quartz结合spring
导入依赖
配置文件配置定时任务
自定义要定时执行的方法
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/

浙公网安备 33010602011771号