使用@scheduled注解实现定时任务

港控/mmm° 2022-01-31 00:53 469阅读 0赞

由于使用的是ssm框架 这里无需添加更多的jar包

只需要在spring配置文件中添加

  1. xmlns:task="http://www.springframework.org/schema/task"

然后在xsi:schemaLocation中添加

  1. http://www.springframework.org/schema/task
  2. http://www.springframework.org/schema/task/spring-task.xsd

添加扫描注解配置(如果已经在扫描范围可以不添加)

  1. <context:component-scan base-package="com.imwoniu.*" />
  2. <!--配置sping定时器开关 -->
  3. <task:annotation-driven />

这样配置就搞定了

接下来只需要在需要定时任务的类上添加@Component注解
在需要定时的方法上添加@Scheduled注解即可

  1. /**
  2. * 定时任务
  3. * @author Administrator
  4. *
  5. */
  6. @Component
  7. public class Task {
  8. /**
  9. * 项目启动时 执行一次 只执行这一次
  10. */
  11. @PostConstruct
  12. public void head() {
  13. System.out.println("--------项目首次启动"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
  14. }
  15. /**
  16. * 项目启动时 执行一次 以后每隔2秒执行一次
  17. */
  18. @Scheduled(fixedRate = 1000*2)
  19. public void aa() {
  20. System.out.println("-------2秒执行一次---------"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
  21. }
  22. /**
  23. * 项目启动后 每隔10秒执行一次
  24. */
  25. @Scheduled(cron = "*/10 * * * * *")
  26. public void bb() {
  27. System.out.println("-------每隔10秒执行一次---------"+new SimpleDateFormat("HH:mm:ss").format(new Date()));
  28. }
  29. }

搞定!

发表评论

表情:
评论列表 (有 0 条评论,469人围观)

还没有评论,来说两句吧...

相关阅读