SpringBoot 使用定时任务
SpringBoot使用定时任务
properties.yml
server: port: 9090 spring: application: name: mydemo jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 mvc: favicon: enabled: false logging: path: ./logs/
pom文件
4.0.0 com.example mydemo 0.0.1-SNAPSHOT jar mydemo http://maven.apache.org UTF-8 1.8 1.8 org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE org.springframework.boot spring-boot-starter-web junit junit test org.springframework.boot spring-boot-maven-plugin repackage
定时任务
package com.example.mydemo.task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@EnableScheduling
public class DemoTask {
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(2); //并行执行个数
taskScheduler.setThreadNamePrefix("hello"); //设置线程前缀
return taskScheduler;
}
@Scheduled(fixedDelay = 5000)
public void cronTask() {
System.out.println(Thread.currentThread().getName() + " 每5秒执行一次");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Scheduled(cron = "*/5 * * * * *")
public void cronTask2() {
System.out.println(Thread.currentThread().getName() + " 每3秒执行一次");
}
}
package com.example.mydemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello world!
*
*/
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.run(args);
}
}