Java中,定时任务Timer简单示例

(1)Timer的方法schedule(task,time),参数task表示所要安排的任务,time表示执行任务的时间。作用:在时间等于或超过time的时候执行且仅执行一次task

(2)schedule(task,time,period)作用:时间等于或超过time时首次执行task,之后每隔period毫秒重复执行一次task

(3)schedule(task,delay)作用:等待delay毫秒后执行且仅执行一次task

(4)schedule(task,delay.period)的作用:等待delay毫秒后首次执行task,之后每隔period毫秒重复执行一次task

创建一个任务:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimerTask;
//创建一个任务
public class MyTimerTask extends TimerTask{
    private String name;
    private int count=0;   //设置执行次数
    public MyTimerTask(String inputName) {  //带参数的构造函数
        this.name=inputName;
    }
    @Override
    public void run() {
        if(count<3){
            //输出当前时间
            Calendar calendar=Calendar.getInstance();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("execute time is:"+simpleDateFormat.format(calendar.getTime()));
            // 输出当前的name 的值
            System.out.println("execute name is:"+name);
            count++;
        }else{
            System.out.println("execute cancel");
            cancel();
        }
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

任务定时定频调用测试:

package com.imooc.timers.timer1;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;

public class MyTimerTaskTest {

    public static void main(String[] args) {
        Timer timer =new Timer();  //创建一个实例
        MyTimerTask myTimerTask=new MyTimerTask("no"); //创建一个MyTimerTask实例
        //通过timer定时定频率执行任务MyTimerTask
        //第一次执行任务在当前时间的2秒前
//        timer.schedule(myTimerTask, 2000L,1000L);

        /**
         * 获取当前时间,并设置成距离当前时间三秒之后的时间
         * 如当前时间是2017-11-10 23:59:57
         * 则设置后的时间则为2017-11-11 00:00:00
         */
        Calendar calendar=Calendar.getInstance();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(calendar.getTime()));
        //获取当前时间3秒之后的时间
        calendar.add(Calendar.SECOND,3);
        //------   schedule的用法-------
        /**
         * 1、在时间等于或者超过time的时候执行且执行一次task
         * 如在2016-11-11 00:00:00执行一次task:打印任务的名字
         */
//        myTimerTask.setName("schedule1");
//        timer.schedule(myTimerTask, calendar.getTime());
        
        /**
         * 2、时间等于或chaoguotime时首次执行task
         * 之后每隔period毫秒重复执行一次task
         * 如在2017-11-11 00:00:00第一次执行task:打印任务名字
         * 之后每隔2秒执行一次task
         */
        myTimerTask.setName("schedule2");
        timer.schedule(myTimerTask, calendar.getTime(),2000L);
        System.out.println("scheduled time is:"+simpleDateFormat.format(myTimerTask.scheduledExecutionTime()));
        //效果一致
//        timer.scheduleAtFixedRate(myTimerTask, calendar.getTime(), 2000L);
        /**
         * 3、等待delay毫秒后执行且进执行一次task
         * 如现在是2017-11-11 00:00:00
         * 则在2017-11-11 00:00:01执行一次task:打印任务名字
         */
//        myTimerTask.setName("schedule3");
//        timer.schedule(myTimerTask, 1000);
        
        /**
         * 4、时间等于或chaoguotime时首次执行task
         * 之后每隔period毫秒重复执行一次task
         * 如在2017-11-11 00:00:00第一次执行task:打印任务名字
         * 之后每隔2秒执行一次task
         */
//        myTimerTask.setName("schedule4");
//        timer.schedule(myTimerTask, 3000L,2000L);
    }

}

其他常用函数:

TimerTask的cancel()函数的作用:取消当前TimerTask里的任务
TimerTask的scheduleExecutionTime()作用:返回此任务最近实际执行的已安排执行的时间,返回值:最近发生此任务执行安排的时间,为long型

Timer的cancel()函数的作用:终止此计时器,丢弃所有当前已安排的任务
Timer的purge()函数的作用:从此计时器的任务队列中移除所有已取消的任务。返回值:从队列中移除的任务数。

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
public class CancleTest {

    public static void main(String[] args) throws InterruptedException {
        Timer timer =new Timer();  //创建一个实例
        MyTimerTask task1=new MyTimerTask("task1"); //创建一个MyTimerTask实例
        MyTimerTask task2=new MyTimerTask("task2"); //创建一个MyTimerTa

        Date date=new Date();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("start time is:"+simpleDateFormat.format(date));

        timer.schedule(task1, 3000,2000);
        timer.schedule(task2, 1000,2000);
        System.out.println("current cancled task num is:"+timer.purge());
        //休眠5秒
        Thread.sleep(5000);
        Date cancleTime=new Date();
        System.out.println("cancle time is:"+simpleDateFormat.format(cancleTime));
        //取消所有任务
//        timer.cancel();
//        System.out.println("Task all canceled!!");
        //取消task2任务
        task2.cancel();
        System.out.println("current cancled task num is:"+timer.purge());
    }

}

 首次计划执行时间小于当前时间scheduleAtFixedRate

public static void main(String[] args) {
        //规定格式
        final SimpleDateFormat ftp=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        //获取当前的具体时间
        Calendar calendar=Calendar.getInstance();
        System.out.println("current time is:"+ftp.format(calendar.getTime()));
        //设置成6秒前时间
        calendar.add(Calendar.SECOND, -6);
        Timer timer=new Timer();
        //第一次执行时间为6秒前,之后每隔2秒执行一次
        timer.schedule(new TimerTask() {
//        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 打印当前的计划执行时间
                System.out.println("schedule exec time is:"+ftp.format(scheduledExecutionTime()));
                System.out.println("task is being executed!");
            }
        },calendar.getTime(),2000);
    }

效果:
current time is:2017-08-20 16-37-14
schedule exec time is:2017-08-20 16-37-14
task is being executed!
schedule exec time is:2017-08-20 16-37-16
task is being executed!
schedule exec time is:2017-08-20 16-37-18
task is being executed!

..............................................

timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                // 打印当前的计划执行时间
                System.out.println("schedule exec time is:"+ftp.format(scheduledExecutionTime()));
                System.out.println("task is being executed!");
            }
        },calendar.getTime(),2000);

效果:
current time is:2017-08-20 16-38-39
schedule exec time is:2017-08-20 16-38-33
task is being executed!
schedule exec time is:2017-08-20 16-38-35
task is being executed!
schedule exec time is:2017-08-20 16-38-37
task is being executed!
schedule exec time is:2017-08-20 16-38-39
task is being executed!
schedule exec time is:2017-08-20 16-38-41
task is being executed!
schedule exec time is:2017-08-20 16-38-43
task is being executed!

--------------------------------------------------------------

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值