多线程之定时器

1.定时器是什么

定时器也是软件开发中的一个重要组件. 类似于一个 "闹钟". 达到一个设定的时间之后, 就执行某个指定好的代码.

定时器是一种实际开发中非常常用的组件.
比如网络通信中, 如果对方 500ms 内没有返回数据, 则断开连接尝试重连.
比如一个 Map, 希望里面的某个 key 在 3s 之后过期(自动删除).
类似于这样的场景就需要用到定时器.

2.标准库中的定时器

  • 标准库中提供了一个 Timer 类. Timer 类的核心方法为 schedule .
  • schedule 包含两个参数. 第一个参数指定即将要执行的任务代码, 第二个参数指定多长时间之后执行 (单位为毫秒).
package thread2;

import java.util.Timer;
import java.util.TimerTask;

public class Test3 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello timer");
            }
        }, 3000);
        System.out.println("hello main");
    }
}

 

3.实现定时器

package thread2;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTimer {
    static class Task implements Comparable<Task> {
        //要执行的任务是什么
        private Runnable runnable;
        //什么时间去执行
        private long time;

        public Task(Runnable runnable, long after) {
            this.runnable = runnable;
            this.time = System.currentTimeMillis() + after;
        }

        public void run() {
            runnable.run();
        }


        @Override
        public int compareTo(Task o) {
            return (int) (this.time - o.time);
        }
    }

    private PriorityBlockingQueue<Task> tasks = new PriorityBlockingQueue<>();

    public void schedule(Runnable runnable, long after) {
        Task task = new Task(runnable, after);
        tasks.put(task);
    }

    //锁,防止cpu一直运行,阻塞等待
    private Object object = new Object();

    //扫描线程
    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    Task task = tasks.take();
                    long curTime = System.currentTimeMillis();
                    if (curTime < task.time) {
                        tasks.put(task);
                        synchronized (object) {
                            object.wait(task.time - curTime);
                        }
                    } else {
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread.start();
    }
}

public class Test4 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        }, 3000);

        System.out.println("hello main");
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Python中,多线程结合定时器通常用于执行周期性的任务或需要在特定时间间隔后响应的场景。Python提供了`threading`模块来支持多线程,并且`schedule`或者`APScheduler`这样的库可以方便地实现定时任务。 1. **多线程**:`threading`模块中的`Thread`类可以用来创建新的线程,每个线程有自己的独立执行路径。当你想在程序中并发执行多个任务时,可以为每个任务创建一个新的线程。 ```python import threading def task_to_run(): # 这里写你的任务代码 pass # 创建一个线程 thread = threading.Thread(target=task_to_run) # 启动线程 thread.start() ``` 2. **定时器**:`schedule`库允许你按照固定时间间隔调度函数的执行。例如: ```python from schedule import every, run_pending import time def job_function(): print("Job executed at", time.ctime()) every(5).seconds.do(job_function) # 每5秒执行一次job_function while True: run_pending() time.sleep(1) # 程序睡眠1秒,等待下一次调度 ``` 如果你想要更高级的定时任务功能,比如支持复杂的调度规则,可以使用`APScheduler`: ```python from apscheduler.schedulers.background import BackgroundScheduler scheduler = BackgroundScheduler() def job_function(): print("Job executed at", time.ctime()) scheduler.add_job(job_function, 'interval', seconds=5) # 每5秒执行一次 scheduler.start() # 开始调度 # 在程序结束前保持调度运行 while True: time.sleep(1) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿瞒有我良计15

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值