定时任务其实能做很多事情,日常签到,提醒,定时获取数据.....。之前就有写定时任务的想法,直到现在才开始付出行动。第一阶段准备写的有:某某平台的签到,和某某平台的数据获取。后续可能会写默认点餐之类的吧(经常忘记点晚饭。。。)
定时任务最简单的办法就是sleep,之前有看到一个段子,“如何获取一天后的时间:Thread.sleep(1000*60*60*24);”
最后选择了SpringBoot+@Scheduled注解的方式,该方式通过Cron表达式设置时间(自行了解),使用起来还是很简单的。
我使用的编辑器是IDEA,创建过程就省略了,默认大家都是可以的。
package kylin; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling //开启自动任务配置 public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@Scheduled(cron="0/5 * * * * ? ") //每5秒执行一次 public void execute(){ System.out.println("*********任务每5秒执行一次进入测试"); }
这里要注意,该方法的类要加上@Component注解
下面是pom.xml(部分),仅供参考
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<dependencies>
<!-- spring-boot使用jetty容器配置begin -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<!-- 排除默认的tomcat,引入jetty容器. -->
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- jetty 容器. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- spring-boot使用jetty容器配置end -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
定时任务到此结束
注意点1:Application.java文件要增加@EnableScheduling 注解,表示开启自动任务
注意点2:@Scheduled(cron="0/5 * * * * ? ") ,其中cron表达式可以实现多种组合,具体的可以查看其它相关教程
如有疑问,欢迎留言
原文:https://www.cnblogs.com/yishilin/p/11127776.html