前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >web项目定时执行任务

web项目定时执行任务

作者头像
用户1215919
发布2018-02-09 10:46:57
7730
发布2018-02-09 10:46:57
举报
文章被收录于专栏:大大的微笑大大的微笑

首先写了个servlet

例如

package com.uap.weixin.service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import com.uap.customer.dao.CustomerDao;
import com.uap.weixin.utils.ToolConfig;

public class TimerServlet implements ServletContextListener{

	
	public TimerServlet() {
		super();
	}

	/** 
	 * 当天
	 * 获取指定时间对应的毫秒数 
	 * @param time "HH:mm:ss" 
	 * @return 
	 */  
	private  long getTimeMillis(String time) {  
	    try {  
	        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");  
	        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");  
	        //String str=dayFormat.format(new Date()) + " " + time;
	        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);  
	        return curDate.getTime();  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	    return 0;  
	}


	public void contextDestroyed(ServletContextEvent arg0) {
		
	}

	public void contextInitialized(ServletContextEvent arg0) {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);  
	    
		  //这里是每隔24小时执行一次;//前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
		    long oneDay = 24 * 60 * 60 * 1000;
		    
		    //初始化延时 ,这里的timer是具体的时间,我把时间写在了配置文件中,ToolConfig.getString("timer")--->改成具体的时间
		    long initDelay  = getTimeMillis(ToolConfig.getString("timer")) - System.currentTimeMillis();
		    initDelay = initDelay > 0 ? initDelay : oneDay + initDelay; 
		    //定时器执行开始
		    executor.scheduleAtFixedRate(new Runnable() {
				
				public void run() {
					//调用此方法,定时获取关注用户
					//这里是定时任务
					CustomerDao.getCustomer();
					System.out.println("正在执行。。。");
				}
			}, initDelay,  
	        oneDay,  
	        TimeUnit.MILLISECONDS);		
	}

}
 <!--这里是web.xml文件中的代码-->
 <listener>
 	<listener-class>com.uap.weixin.service.TimerServlet</listener-class>
 </listener>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档