关于springboot如何做一个定时任务

本文介绍如何使用SpringBoot实现定时任务,通过ServletContextListener监听器和@ServletComponentScan注解,结合CustomerService业务逻辑,实现每月20日的用户奖金发放功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于springboot如何做一个定时任务

  1. 首先我们需要用到Tomcat的监听器ServletContextListener,我们将需要写的一个定时任务类继承ServletContextListener,ServletContextListener有两个重写方法,分别是contextInitialized和contextDestroyed,将你需要服务器开始时要监控的定时任务写在contextInitialized方法中,将你需要在服务器关闭时做的一些处理写在contextDestroyed,就可以很方便的完成你的需求,代码如下:

@WebListener
public class ContextListener implements ServletContextListener {
	
	@Autowired
	private CustomerService customerServiceImpl;
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
    	// 定时任务
    			Timer timer = new Timer();
    			timer.schedule(new TimerTask() {
    				@Override
    				public void run() {
    					Calendar cal = Calendar.getInstance();
    					int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
    					if (day_of_month == 20) {
    						customerServiceImpl.userBonus();
    					} 
    				}
    			}, 0, 3600 * 24 * 1000);
    }
 
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
 
    	System.out.println("Destroyed");
    }
}

2.@WebListener注解是springboot监听器的一个注解,所有监听器实体类都需要加上这个注解,并且在springboot的启动类Application当中,还需要加上一个能扫描全局的监听器过滤器的一个注解,那就是@ServletComponentScan,代码如下:

@ServletComponentScan
@SpringBootApplication
@MapperScan("*.mapper")
public class MMApplication {

	public static void main(String[] args) {
		SpringMMApplication.run(MMApplication.class, args);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值