SpringBoot定時任務:每隔兩秒鐘列印一次當前時間
阿新 • • 發佈:2021-07-17
SpringBoot定時任務
1、開啟定時任務
在SpringBootApplication類中添加註解
例如:
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * @title 專案入口(啟動類) * @Desc 用於專案的啟動和終止 * @EnableScheduling: 開始定時任務 * @SpringBootApplication:標識為SpringBoot應用 * @author <a href="mailto:[email protected]">avaos.wei</a> * @Date 2020-03-25 13:25 **/ @EnableScheduling @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
2、定時任務
在類上添加註解:@Component
在方法上添加註解:@Scheduled
例如:
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.Date;/** * @title 定時任務 * @Desc 用於定時的執行某一任務 * @author <a href="mailto:[email protected]">avaos.wei</a> * @Date 2020-03-25 13:31 * */ @Component public class TestTask { /** * @title 定時列印 * @desc 每隔兩秒鐘列印一次當前時間 * @param : * @return * @author <a href="mailto:[email protected]">avaos.wei</a> * @date 2020-03-25 13:32*/ @Scheduled(fixedRate = 2000) public void output() { System.out.println(String.format("當前時間:%s", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))); } }