Java实现Timer定时器功能

3种定时器:
1. 设置指定任务在多少毫秒之后执行
2. 设置指定任务在多少毫秒之后,以多少毫秒为一周期持续执行
3. 设置指定任务在今天或明天几点开始执行,并且以多少毫秒为一周期持续执行

1. 设置指定任务在多少毫秒之后执行
实现方法:

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        System.err.println(sdf.format(new Date()));
        timer1();
    }
    
    public static void timer1() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                System.out.println("-------设定要指定任务-timer1--------" + sdf.format(new Date()));
            }
        }, 5000);	// 5000为延时多少毫秒执行,delay
    }

效果图:
在这里插入图片描述
2. 设置指定任务在多少毫秒之后,以多少毫秒为一周期持续执行
方法一:使用Timer.schedule()

    public static void timer2(){
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("-------设定要指定任务-timer2--------" + sdf.format(new Date()));
            }
        },3000,5000); // 3000为延时多少毫秒delay,5000为多少毫秒为一周期period
    }

效果:
在这里插入图片描述

方法二:使用Timer.scheduleAtFixedRate()
实现方法:

    public static void timer3(){
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("-------设定要指定任务-timer3--------" + sdf.format(new Date()));
            }
        },3000,5000);
    }

效果:
在这里插入图片描述
3. 设置指定任务在今天或明天几点开始执行,并且以多少毫秒为一周期持续执行
实现方法:
定时今天15:48:00开始执行任务、然后以1000毫秒为周期执行

    public static void timer4(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 15);     //时
        calendar.set(Calendar.MINUTE,48);   //分
        calendar.set(Calendar.SECOND,0);    //秒
        Date time = calendar.getTime(); //得出执行任务的时间,此处为今天的12:00:00
        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("-------设定要指定任务-timer4--------" + sdf.format(new Date()));
            }
        },time, 1000);   //这里设定将延时每天固定执行
    }

效果:
在这里插入图片描述

定时器工具类
各类定时器方法,及定时器终止方法
有多个定时器,终止指定定时器实现方法如下stopTimer()方法

package com.gaohan.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;

import java.text.ParseException;
import java.util.*;

/**
 * @author gaohan
 * @version 1.0
 * @date 2020/5/8 22:59
 */
public class TimerUtils {
    private static Logger logger = (Logger) LogManager.getLogger(TimerUtils.class);

    private Timer timer = new Timer();

    public static Map<String, TimerTask> map = new HashMap<>();    //用来存储所有定时器

    /**
     * 延时执行定时任务
     * @param uuid  定时任务id
     * @param delay 延时时间(毫秒)
     */
    public void startTimerDelay(String uuid, long delay) throws Exception {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                logger.info("-------设定要指定任务--------");
            }
        };
        timer.schedule(task, delay);
//        TimerController.map.put(uuid, task);
    }

    /**
     * 延时并按周期循环执行定时任务
     * @param uuid  定时任务id
     * @param delay 延时时间(毫秒)
     * @param period  循环间隔时间(毫秒)
     * @param str   打印信息
     * @throws InterruptedException
     * @throws ParseException
     */
    public void startTimerDelayPeriod(final String uuid, long delay, long period, final String str) throws InterruptedException, ParseException {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                logger.info("====>  " + uuid + str);
            }
        };
        timer.scheduleAtFixedRate(task, delay, period);
        map.put(uuid, task);
    }

    /**
     * 设置指定任务TimerTask在今天指定时间开始执行,并且以固定的period毫秒为周期执行
     * @param uuid  定时任务id
     * @param period 周期(毫秒)
     * @param hour      几点
     * @param minute    几分
     * @param second    几秒
     */
    public void startTimerDelayPeriodByTime(String uuid, long period, int hour, int minute, int second){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, hour);     //时
        calendar.set(Calendar.MINUTE, minute);   //分
        calendar.set(Calendar.SECOND, second);    //秒
        Date time = calendar.getTime(); //得出执行任务的时间,此处为今天的12:00:00
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("-------设定要指定任务--------");
            }
        };
        timer.scheduleAtFixedRate(task, time, period);   //这里设定将延时每天固定执行
        map.put(uuid, task);
    }

    /**
     * 停止定时任务
     * @param uuid  定时任务id
     */
    public void stopTimer(String uuid) {
        TimerTask task = map.get(uuid);
        if (task != null) {
            task.cancel();
            logger.info("====>  结束定时任务[" + uuid + "]");
            map.remove(uuid);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值