java定时任务

有时候,我们需要定时执行某项任务。比如每天晚上1点执行数据同步;每隔30分钟清理一次系统缓存等等。

该任务可通过java.util.TimerTask来实现。例如本文举例每天在系统配置的时间执行同步任务。

1. 任务

package casco.com.tse.sh;

/**
* 同步的类型
* @author Joshua
*
*/
public enum SyncType {

/*******
* 全部
*/
ALL,
/******
* 岗位
*/
GZ,
/***********
* 岗位-用户映射
*/
GZUSER,
/*******
* 用户
*/
USER
}

import org.apache.log4j.Logger;

/**************
* synchronize interface
* 同步单一线程
* @author Joshua
*
*/
public class Sync implements Runnable {

@SuppressWarnings(“unused”)
private Sync(){}

public Sync(SyncType synctype) {
super();
this.synctype = synctype;
}

/***************
* 是否正在同步,保证同一时刻只有一个同步线程
*/
public static boolean sync_running = false;

private static final Logger logger = Logger.getLogger(SynchLogic.class);

/*********
* 同步类型
*/
private SyncType synctype;

public void run() {
// TODO Auto-generated method stub
if (sync_running) {
return;
}
try {
// synchronized (sync_running) {
// sync_running = true;
// }
sync_running = true;
System.out.println(“sync_running:”+sync_running);
SynchLogic sLogic = new SynchLogic();
if (synctype.equals(SyncType.ALL)) {
boolean suc = true;
if (!sLogic.synccourse()) {
suc = false;
}
if (!sLogic.syncuser()) {
suc = false;
}
if (!sLogic.syncgz()) {
suc = false;
}
if (!sLogic.syncgzuser()) {
suc = false;
}
if (!sLogic.synchsgz()) {
suc = false;
}
if (suc == false) {
throw new Exception(“synchronize failed!”);
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
logger.error(e.toString());
} finally {
// synchronized (sync_running) {
// sync_running = false;
// }
sync_running = false;
}
}

public void setSynctype(SyncType synctype) {
this.synctype = synctype;
}

public SyncType getSynctype() {
return synctype;
}

}

2. 定时任务检查,如果符合条件,启动线程任务

/**
*
*/
package casco.com.tse.sh;

import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import casco.com.tse.hibernate.dao.tools.ReadProperty;

/**
* scheduled synchronized task
* @author Joshua
*
*/
public class ScheduleSync extends TimerTask {

// private final static int SCHEDULE_HOUR = Integer.parseInt(ReadProperty.getKey(“AutoSyncHour”));

private Logger logger = Logger.getLogger(ScheduleSync.class);

@Override
public void run() {
// TODO Auto-generated method stub
logger.info(“[计划任务] 同步更新程序”);
// Calendar calendar = Calendar.getInstance();
// if (SCHEDULE_HOUR == calendar.HOUR_OF_DAY) {
if (Sync.sync_running) {
logger.info(“[计划任务] ” + new Date() + ” 同步更新正在执行,本次计划任务未执行!”);
} else {
Thread sThread = new Thread(new Sync(SyncType.ALL));
sThread.start();
logger.info(“[计划任务] 系统启动同步成功,详细信息请查询系统日志!”);
}
// }
}

}

3.  定时任务-继承ServletContextListener接口

/**
*
*/
package casco.com.tse.sh;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

import casco.com.tse.hibernate.dao.tools.ReadProperty;

/**
* schedule task
* @author Joshua
*
*/
public class TimerListener implements ServletContextListener {

private final static int SCHEDULE_HOUR = Integer.parseInt(ReadProperty.getKey(“AutoSyncHour”));

private Timer timer;

private final int PERIOD = 24*60*60*1000;

private ScheduleSync syncTask;

private Logger logger = Logger.getLogger(TimerListener.class);

/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
timer.cancel();
logger.info(“定时任务已销毁!”);
}

/* (non-Javadoc)
* @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
timer = new Timer(true);
syncTask = new ScheduleSync();
logger.info(“定时器已启动”);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, Calendar.MONTH, Calendar.DATE, SCHEDULE_HOUR, 0);
calendar.add(Calendar.DATE, 1);
timer.schedule(syncTask, calendar.getTime(), PERIOD);
logger.info(“自动更新程序已添加至任务调度计划!”);
}

}

4. web.xml设置在系统启动时启动该任务

<listener>
<listener-class>casco.com.tse.sh.TimerListener</listener-class>
</listener>

 

This entry was posted in Computer, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s