Springboot定时任务调用

和spring框架相比,spring boot通过简约化的配置使得创建一个定时任务变得简单。通过开启相应的注解就可以进行相应的定时任务的操作。

1.在spring boot的启动类加上开启定时任务的注解@EnableScheuling

@SpringBootApplication
@Component
@ComponentScan
@EnableScheduling
public class ServerApplication {
    private static final Logger logger = LoggerFactory.getLogger("adminLogger");

	public static void main(String[] args) {
	   SpringApplication app = new SpringApplication(ServerApplication.class);  
       app.addListeners(new StartApplicationListener());  
       app.run(args);  
	}
    @Scheduled(cron = "20 46 11 * * ?" )
	public void timerToNow(){
	    AditionService aditionService = (AditionService)SpringUtil.getBean(AditionService.class);
		BaseResponse res = aditionService.timerToNow();
		logger.info(res.toString());
	}
}

2.定义定时任务的注解@Scheduled

在这里解释一下这个注解里面的参数,各个参数所代表的值是:秒,分,时,天,月,周。

所以在这里我定义的就是在11点46分20秒执行定时任务。在public void timerToNow(){}方法中定义你的逻辑处理方式,我这边需要在定义好的时间上获取一个月前的数据,并删除相应的表里面的数据。

@Component
public class AditionService {

    @Autowired
    private PayAcceptOrderOldMapper acceptOrderOldMapper;
    
    @Autowired
    private PayAcceptOrderMapper acceptOrderMapper;

	@Transactional
	public BaseResponse timerToNow(){
		PayAcceptOrderOld payAcceptOrderOld =new PayAcceptOrderOld();
		int flag =acceptOrderOldMapper.insertAddition(payAcceptOrderOld);
		int delfalg = acceptOrderMapper.deleteMonthData();
		if(flag==delfalg){
			System.out.println("adminadmin");
			return BaseResponse.success();
		}else{
			throw new RuntimeException("商户信息添加失败");
		}
	}
}

这里需要注意的是,如果你是多表操作,请务必加上事务的注解,并且在错误的时候抛出相应的异常。

其次,我想说一下查询一张表数据的前30天的数据添加到另外一张表的同时,删除相应表中的数据。其实也就是我上面代码的执行过程。

INSERT INTO pay_accept_order_old SELECT
     t.*, getdate()
	 FROM
	 pay_accept_order t
	 WHERE
	 t.last_updated_time <= dateadd(day,-30, getdate())

查询order表中30天前的数据插入到orderold表中。由于mybatis的关系,小于号我直接转义字符代替了。

<delete id="deleteMonthData">
     delete from pay_accept_order WHERE last_updated_time <= dateadd(day,-30, getdate())
  </delete>

删除相应的30天前的数据,通过比对两者的数据操作条数进行判断,不成功则事务回滚。

相比繁杂的配置,springboot通过少量的配置就达到了相同的结果。

猜你喜欢

转载自blog.csdn.net/T_james/article/details/80049405
今日推荐