SpringBoot定时任务:每隔两秒钟打印一次当前时间
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:avaos.wei@gmail.com">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:avaos.wei@gmail.com">avaos.wei</a> * @Date 2020-03-25 13:31 * */ @Component public class TestTask { /** * @title 定时打印 * @desc 每隔两秒钟打印一次当前时间 * @param : * @return * @author <a href="mailto:avaos.wei@gmail.com">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()))); } }

浙公网安备 33010602011771号