在tomcat启动时启动定时任务ServletContextListener

package com.zzht.cctv.defect.calculate.schedule;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import javax.annotation.Resource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

@WebListener
public class TimerListener implements ServletContextListener {
	 private static final Logger LOGGER = LoggerFactory.getLogger(TimerListener.class);
	 private Timer timer = null;
	 @Value("${cctvAi.schedulTime}")
	 private String schedulTime;
	 @Resource
	 private VideoAITask videoAITask;
	 @Override  
	 public void contextInitialized(ServletContextEvent event) {
         timer = new Timer(true);
         LOGGER.info("定时器已启动,开始进行判读");
         //设置执行时间
         Calendar calendar = Calendar.getInstance();
         int year = calendar.get(Calendar.YEAR);
         int month = calendar.get(Calendar.MONTH);
         int day = calendar.get(Calendar.DAY_OF_MONTH);//每天
         //定制每天执行,具体时间读取配置
         String timeArr[] = schedulTime.split(":");
         calendar.set(year, month, day, Integer.valueOf(timeArr[0]), Integer.valueOf(timeArr[1]), Integer.valueOf(timeArr[2]));
         Date date = calendar.getTime();
         //执行任务
         timer.schedule(videoAITask, date);
	 }

说明:需实现ServletContextListener接口,并实现contextInitialized方法,还要加上@WebListener注解,并且springboot的启动类上要加上@ServletComponentScan注解,扫描到这个监听

在videoAITask类中编写定时要做的事

package com.zzht.cctv.defect.calculate.schedule;

import java.util.TimerTask;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.zzht.cctv.common.util.HttpRequest;


@Component

public class VideoAITask extends TimerTask {
	

	@Value("${cctvAi.url}")
    private String url;
	


	@Override
	public void run() {
		String href = url + "cctv/ai/dealAIVideo";
		try {
			HttpRequest.sendPost(href, "isSchedul=1");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(java,java,springboot)