java 定时任务 (timer和timetask,quartz,spring,LinuxCron)

</pre>在Java中,实现定时任务有多种方式,,Timer和TimerTask、Spring、QuartZ、Linux Cron。<p></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">以上4种实现定时任务的方式,Timer是最简单的,不需要任何框架,仅仅JDK就可以,缺点是仅仅是个时间间隔的定时器,调度简单;Spring和QuartZ都支持cron,功能都很强大,Spring的优点是稍微简单一点,QuartZ的优点是没有Spring也可使用;Linux Cron是个操作系统级别的定时任务,适用于所有操作系统支持的语言,缺点是精度只能到达分钟级别。</p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px">本文直介绍<span style="font-family:Arial; font-size:14px; line-height:26px">Timer和TimerTask、<span style="font-family:Arial; font-size:14px; line-height:26px">QuartZ</span></span></p><p style="margin-top:0px; margin-bottom:0px; padding-top:0px; padding-bottom:0px; font-family:Arial; font-size:14px; line-height:26px"></p><h1 style="margin:0px; padding:0px; font-family:Arial; line-height:26px">Timer和TimerTask</h1><div></div><pre name="code" class="java">package timertask;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TimerTest extends TimerTask {

	@Override
	public void run() {
		System.out.println(i++);
		
	}
	
	private Timer timer;
	private int i=0;
	public static void main(String[] args) {
		TimerTest tt=new TimerTest();
		tt.timer=new Timer();
		tt.timer.schedule(tt, new Date(),1000);
		//立刻开始执行timerTest任务,执行完本次任务后,隔2秒再执行一次    
        //timerTest.timer.schedule(timerTest,new Date(),2000);              
        //一秒钟后开始执行timerTest任务,只执行一次    
        //timerTest.timer.schedule(timerTest,1000);              
        //一秒钟后开始执行timerTest任务,执行完本次任务后,隔2秒再执行一次    
        //timerTest.timer.schedule(timerTest,1000,2000);              
        //立刻开始执行timerTest任务,每隔2秒执行一次    
        //timerTest.timer.scheduleAtFixedRate(timerTest,new Date(),2000);             
        //一秒钟后开始执行timerTest任务,每隔2秒执行一次    
        //timerTest.timer.scheduleAtFixedRate(timerTest,1000,2000);    
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//结束任务执行,程序终止    
        tt.timer.cancel();    
        //结束任务执行,程序并不终止,因为线程是JVM级别的    
        //timerTest.cancel(); 
		System.out.println("你好");
	}
	
}

quartz 的实现。(测试时,需要quartz,slf4j,log4j的架包)

定时任务执行的对象 要继承与job
package timertask.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.quartz.Calendar;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class AutoSendo implements Job{

	@Override
	public void execute(JobExecutionContext jobexecutioncontext)
			throws JobExecutionException {
		//定时任务执行的动作。输出数据
		String string=(String) jobexecutioncontext.getJobDetail().getJobDataMap().get("key");
		System.out.println(string);
//		System.out.println("fdsfsdfsdfsd");
	}

}

2,执行定时任务

package timertask.quartz;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.bouncycastle.jce.provider.JDKDSASigner.noneDSA;
import org.quartz.CronExpression;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;

public class QuartzSchedulerUtil {
	
	public static void launchTask() throws Exception{
				SchedulerFactory factory =new StdSchedulerFactory();
				//一种,cronTrigger获得方式一
				CronTriggerImpl cronTrigger=new CronTriggerImpl();
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				//第二种cronTrigger的获得方式
//					cronTrigger=TriggerBuilder.newTrigger().withIdentity("sss").withSchedule(CronScheduleBuilder.cronSchedule("0/2 * * * * ?")).build();
				cronTrigger.setCronExpression("0/30 * * * * ? ");
				cronTrigger.setName("sssss");
				cronTrigger.setStartTime(new Date());
				Class<Job> job1=(Class<Job>) Class.forName("timertask.quartz.AutoSendo");
				System.out.println(job1.newInstance());
				JobBuilder jb= JobBuilder.newJob(job1).withIdentity("sssssss");
				jb.usingJobData("key", "value");
				JobDetail job=jb.build();
				Scheduler scheduler=factory.getScheduler();
				Date date =scheduler.scheduleJob(job, cronTrigger);
				System.out.println(sdf.format(date)); 
				scheduler.start();
				//立即发送方法
				scheduler.triggerJob(job.getKey());;
				//停止定时任务
				scheduler.unscheduleJob(cronTrigger.getKey());
	}
	public static void main(String[] args)  throws Exception {
		QuartzSchedulerUtil.launchTask();
	}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值