Java Timer timer


Timer

1. Overview timer

  • Timer, you can set the thread execution at a time something or a certain time, every specified time interval repeatedly to do something;

2. Timer class

  • Timer class can implement thread scheduling tasks for the future and is performed in the background thread, you can schedule a task to perform, or repeated periodically;
  • java.util.Timer,详见: Class Hours ;

3. Constructor

Construction method Explanation
Timer() Constructs a timer

4. Members method

return value Method name Explanation
void schedule(TimerTask task, long delay) Schedule tasks specified execution after a specified delay
void schedule(TimerTask task, long delay, long period) Start after a specified delay, re-execute the tasks specified fixed delay execution
void schedule(TimerTask task, Date time) Schedules the specified task execution at a specified time
void schedule(TimerTask task, Date firstTime, long period) Starting at the specified time, to perform the specified task for repeated fixed-delay execution

5. Java Examples

import java.text.SimpleDateFormat;
import java.util.*;

public class Test {
    public static void main(String[] args) {
        //1.设置一个定时器,2秒后启动,只执行一次
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                for (int i = 10; i >= 0; i--) {
                    System.out.println("倒数:" + i);
                    try {
                        Thread.sleep(1000);
                    } catch (Exception e) {
                    }
                }
                System.out.println("嘭......嘭......");
                //任务执行完毕,终止计时器
                t.cancel();
            }
        }, 2000);

        //2.设置一个定时器,5秒后开始执行,每一秒执行一次
        Timer t2 = new Timer();
        t2.schedule(new TimerTask() {
            @Override
            public void run() {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(sdf.format(new Date()));
            }
        }, 5000, 1000);

        //3.设置一个定时器,在2030年01月01日零时开始执行,每隔24小时执行一次
        Timer t3 = new Timer();
        Calendar c = new GregorianCalendar(2030, 1 - 1, 1, 0, 0, 0);
        Date d = c.getTime();

        t3.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("搜索全盘......");
            }
        }, d, 1000 * 3600 * 24);
    }
}
/*
部分输出
倒数:10
倒数:9
倒数:8
倒数:7
2020-03-08 20:50:12
2020-03-08 20:50:13
倒数:6
2020-03-08 20:50:14
倒数:5
2020-03-08 20:50:15
倒数:4
2020-03-08 20:50:16
倒数:3
2020-03-08 20:50:17
倒数:2
2020-03-08 20:50:18
倒数:1
2020-03-08 20:50:19
倒数:0
2020-03-08 20:50:20
嘭......嘭......
2020-03-08 20:50:21
2020-03-08 20:50:22
...
 */
Published 201 original articles · won praise 200 · Views 6359

Guess you like

Origin blog.csdn.net/Regino/article/details/104726585