java定时器timer 取消_JAVA定时器Timer的使用

本文详细介绍了如何使用Java Timer类实现定时任务,包括单次执行、周期性执行的示例,并演示了TaskMaster和TaskTask类的使用。通过创建TaskMaster实例,设置定时日期并调用相关方法,实现了定时器任务的日常执行。
摘要由CSDN通过智能技术生成

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值