spring定时任务开启步骤

首先在配置文件头部的必须要有:

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

 

其次xsi:schemaLocation必须为其添加:

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

 

然后spring扫描过程必须涵盖定时任务类所在的目录:  加上定时任务类所在包,我的是在common下

  • <context:component-scan base-package="com.**.service,com.**.common">
    <!-- 去掉controller扫描 -->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

     

 

com.xx.common属于定时任务类的父级甚至更高级 

然后设置动作启用定时任

<task:annotation-driven/>

 

最后设置任务类

@Component
@EnableAsync
@EnableScheduling
public class BloodTimer {

    @Autowired
    private UserServive userServive;

    /**
     *     定时任务,读取设备数据
     */
    @Scheduled(fixedDelay = 1 * 60 * 1000)
    @Async
    public void getPppeData() {
        try {
            System.out.println("执行了定时任务");
            userService.getUser();
          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
  
  
   /**
     *     定时任务,定时删除操作日志
     *    每天6点执行一次,删除2年前日志,只保留近2年日志
     */
    @Scheduled(cron = "0 0 6 * * ?")
    public void deleteLog() {
        try {
            System.out.println("执行了定时删除日志信息");
            logMessageService.deleteLogTimer();      
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

 


}

 

posted @ 2021-06-18 15:56  登风360  阅读(506)  评论(0编辑  收藏  举报