定时器

一、Timer

1.1简介

java.lang.Object
 java.util.Timer

一种工具,线程用其安排以后在后台线程中执行的任务。
1.生活中的定时器 闹钟 定时家电 定时炸弹
2.开发中定时器使用的场景 A.定时发送邮件 B.定时提交代码 C.定时收集日志信息 D.秒杀
3.使用步骤
A.创建一个任务对象
B.实例化定时器对象
C.将任务对象提交的定时器中

1.2 常用的方法

方法名称 方法描述
public void schedule(TimerTask task, Date time) 安排在指定的时间执行指定的任务(执行一次)
public void schedule(TimerTask task, Date fifirstTime, long period) 安排指定的任务在指定的时间开始进行重复的固定延迟执行(执行多次)
public void schedule(TimerTask task, long delay) 安排在指定延迟后执行指定的任务

1.3 使用

package com.xxx.test1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.TimerTask;

public class MyTimerTask extends TimerTask {

    private int num = 1;

    @Override
    public void run() {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("1.txt"));
            bw.write(num+"");
            num++;
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

package com.xxx.test1;

import java.util.Timer;

public class Exe {
    public static void main(String[] args) {
        //实例化定时对象
        Timer timer = new Timer();
        //实例化任务对象
        MyTimerTask task = new MyTimerTask();
        //将任务对象提交定时器
        timer.schedule(task,1000,1000);
        //停止定时器
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

posted @ 2022-10-25 19:24  Rix里克斯  阅读(238)  评论(0)    收藏  举报