java定时任务Timer和TimerTask使用详解
更新时间:2020年07月31日 09:47:25 作者:我爱娃哈哈
这篇文章主要为大家详细介绍了java定时任务Timer和TimerTask使用方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
timer和timertask是jdk自带的定时任务实现,无需导入第三方jar包来完成
1、指定多久之后执行此任务,注意:只会执行一次
public class TimerTest { Timer timer; public TimerTest(int time){ timer = new Timer(); timer.schedule(new timerTaskTest(),time*1000);//timer.schedule(执行的方法,延迟多久执行(ms)) } public static void main(String[] args) { System.out.println("timer begin..."); new TimerTest(3); } class timerTaskTest extends TimerTask{ @Override public void run() { System.out.println("time's up!!"); } } }
2、在指定的时间执行任务
public class TimerTest1 { Timer timer; public TimerTest1(){ Date time = getTime(); System.out.println("指定时间time="+time); timer = new Timer(); timer.schedule(new TimerTaskTest1(),time);//timer.schedule(执行的方法,要执行的时间) } public Date getTime(){//设置执行时间 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR,5); calendar.set(Calendar.MINUTE,46); calendar.set(Calendar.SECOND,00); Date time = calendar.getTime(); return time; } public static void main(String[] args) { new TimerTest1(); } class TimerTaskTest1 extends TimerTask{ public void run() { System.out.println("指定时间执行线程任务..."); } } }
3、在延迟指定时间后以指定的间隔时间循环执行定时任务
public class TimerTest2 { Timer timer; public TimerTest2(){ timer = new Timer(); timer.schedule(new TimerTaskTest2(),1000,2000);//tiemr.schedule(执行的方法,延迟时间,多久执行一次) } class TimerTaskTest2 extends TimerTask{ @Override public void run() { System.out.println("本次任务执行时间"+new Date()); } } public static void main(String[] args) { new TimerTest2(); } }
到这里定时任务实现类已经完成,如果是web项目,则需要在web.xml中配置启动
<listener> <listener-class>com.sxl.ContextListener</listener-class> </listener>
配置完成即可。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
解决@RequestMapping和@FeignClient放在同一个接口上遇到的坑
这篇文章主要介绍了解决@RequestMapping和@FeignClient放在同一个接口上遇到的坑,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-07-07java、spring、springboot中整合Redis的详细讲解
这篇文章主要介绍了java、spring、springboot中整合Redis的详细讲解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2021-04-04Spring Cloud Gateway动态路由Apollo实现详解
这篇文章主要为大家介绍了Spring Cloud Gateway动态路由通过Apollo实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10
最新评论