日期:2014-05-18  浏览次数:20701 次

如何在每月的10号让程序做某一件事
如何在每月的10号让程序做某一件事

------解决方案--------------------
java.util.Timer t = new Timer();

t.shechde(new TaskA(), new Date(107,7,25,8,0,0), 1000*60*60*24);

application.setAttribute( "task ", t);


--------------------------------
class TaskA() extends TimerTask{
public void run(){
Date date = new Date();
if(date.getDate()==10){
doSomething();
}
}

}
------解决方案--------------------
jdring.非常好用!上网下个jdring.jar
下面是类似代码:
private static AlarmManager mgr = new AlarmManager();
private static AlarmEntry entry;
//AlarmManager.addAlarm(minute, hour, day of month, month, day of week, year,AlarmListener)
entry= mgr.addAlarm(-1 , -1 , new Integer(10), -1, -1, -1, new ExecuteJob());

new ExecuteJob())是你要执行的东西
------解决方案--------------------
使用Spring的quartz
------解决方案--------------------
Timer无法指定具体的时间执行任务。所以采用quartz是不错的选择。
下载个quartz.jar
cron表达式:每月的10号: 0 0 0 10 * ?
两个步骤:
1:编写你需要执行的任务:
SimpleQuartzJob.java:
public class SimpleQuartzJob implements Job {

public SimpleQuartzJob() {
}

public void execute(JobExecutionContext context) throws JobExecutionException {
System.out.println( "In SimpleQuartzJob - executing its JOB at "
+ new Date() + " by " + context.getTrigger().getName());
}
}

2:设置cron表达式,run it:
CronTriggerRunner.java:

import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

/**
*/
public class CronTriggerRunner {

public void task() throws SchedulerException
{
// Initiate a Schedule Factory
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
// Retrieve a scheduler from schedule factory
Scheduler scheduler = schedulerFactory.getScheduler();

// current time
long ctime = System.currentTimeMillis();

// Initiate JobDetail with job name, job group, and executable job class
JobDetail jobDetail = new JobDetail( "jobDetail1 ", "jobDetailGroup1 ", SimpleQuartzJob.class);
// Initiate CronTrigger with its name and group name
CronTrigger cronTrigger = new CronTrigger( "cronTrigger ", "triggerGroup1 ");
try {
// setup CronExpression
CronExpression cexp = new CronExpression( "0 0 0 10 * ? ");
// Assign the CronExpression to CronTrigger
cronTrigger.setCronExpression(cexp);
} catch (Exception e) {
e.printStackTrace();
}
// schedule a job with JobDetail and Trigger
scheduler.scheduleJob(jobDetail, cronTrigger);

// start the scheduler
scheduler.start();
}

public static void main (String args[])
{
try {
CronTriggerRunner qRunner = new CronTriggerRunner();
qRunner.task();
} catch (Exception e)
{
e.printStackTrace();
}
System.out.println( "is run! ");