JAVA定时器Timer的使用
来源:互联网 发布:什么是大数据举例说明 编辑:程序博客网 时间:2024/05/01 10:21
java定时器的实现主要是靠Timer来实现的
Timer中的常用的几个方法:
/**
*任务在delay时间后执行且只执行一次
**/
public void schedule(TimerTask task,long delay);
/**
*任务在时间为date执行且只执行一次,如果date为过去时间,则任务立即执行。
**/
public void schedule(TimerTask task,Date date);
/**
*任务以peroid为周期重复执行,第一次执行延误delay时间
**/
public void schedule(TimerTask task,long delay,long peroid);
/**
*任务以peroid为周期重复执行,第一次执行时间为firstTime,若firstTime为过去时间,则任务立即执行
**/
public void schedule(TimerTask task,Date firstTime,long peroid);
demo:
TimerTask类
package com.cn.lyb.schedule;import java.text.SimpleDateFormat;import java.util.Date;import java.util.TimerTask;/** * 定时器 * @author liyabin * */public class Task extends TimerTask{ public void run() { SimpleDateFormat sf=new SimpleDateFormat("hh-mm-ss"); System.out.println("任务执行:"+sf.format(new Date())); System.out.println("now let's begin to excute a timer task"); }}package com.cn.lyb.schedule;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.Timer;import java.util.logging.SimpleFormatter;public class TaskMaster { private Calendar calendar=Calendar.getInstance(); private static final long PEROID_DAY=24*60*60*1000; public TaskMaster(){ int year=calendar.get(Calendar.YEAR); int month=calendar.get(Calendar.MONTH); int date=calendar.get(Calendar.DAY_OF_MONTH); calendar.set(year,month,date,13,58,30); System.out.println("--------"); Date ecDate=calendar.getTime(); ecDate=this.addDate(ecDate, 1); Timer timer=new Timer(); Task task=new Task(); SimpleDateFormat sf=new SimpleDateFormat("hh-mm-ss"); System.out.println(sf.format(new Date())); ///若是希望每天定时执行则将peroid参数改为PEROID_DAY即可 timer.schedule(task,ecDate,6000); } private Date addDate(Date date,int num){ Calendar startDt=Calendar.getInstance(); startDt.setTime(date); startDt.set(Calendar.DAY_OF_WEEK_IN_MONTH,num); return startDt.getTime(); } public static void main(String[] args){ System.out.println("主程序"); new TaskMaster(); }
执行结果如下:
主程序
02-11-19
任务执行:02-11-19
now let’s begin to excute a timer task
任务执行:02-11-25
now let’s begin to excute a timer task
任务执行:02-11-31
now let’s begin to excute a timer task
阅读全文
0 0
- java timer定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- Java Timer 定时器的使用
- 【Java】定时器Timer的使用
- java定时器Timer的使用
- Java Timer定时器的使用
- JAVA定时器Timer的使用
- Java 定时器 Timer 的使用
- java定时器的使用(Timer)
- java定时器的使用(Timer)
- java 定时器的使用(Timer)
- poj2229
- 初识KnockoutJS
- Android Bitmap大量使用不产生OOM之“加载大图片资源优化”
- windows下编译openssl
- 解决Android 5.1物理键盘与软键盘的同时使用
- JAVA定时器Timer的使用
- Java学习总结之基本语法
- 配置Django框架为生产环境的注意事项(DEBUG=False)
- 回归分析
- PyQGIS开发 -- 环境搭建
- SQL 语句中的in、find_in_set、like的区别
- 【多线程】newScheduledThreadPool线程池比较scheduleAtFixedRate和scheduleWithFixedDelay
- const vector<int>::iterator和vector<int>::const_iterator的区别
- 欢迎使用CSDN-markdown编辑器