android Timer TimerTask source code


In the library that comes with jdk, there are two technologies that can implement timing tasks. One is to use Timer, and the other is ScheduledThreadPoolExecutor.
This article first explains Timer.

Timer

1. Use of Timer

private Timer timer = new Timer();
                timer.scheduleAtFixedRate(new TimerTask() {
    
    
                    @Override
                    public void run() {
    
    
                        Log.d(TAG,"=======: "+i++);
                    }
                },3000,3000);
执行后:
2020-01-01 00:11:53.053 4230-4230/com.example.demoo D/demo: Touch
2020-01-01 00:11:56.055 4230-4258/com.example.demoo D/demo: =======: 0
2020-01-01 00:11:59.054 4230-4258/com.example.demoo D/demo: =======: 1
2020-01-01 00:12:02.054 4230-4258/com.example.demoo D/demo: =======: 2
2020-01-01 00:12:05.055 4230-4258/com.example.demoo D/demo: =======: 3
2020-01-01 00:12:08.054 4230-4258/com.example.demoo D/demo: =======: 4   

通过往Timer提交一个TimerTask的任务,同时指定多久后开始执行以及执行周期,我们可以开启一个定时任务。         

ScheduleAtFixedRate parameters:
1. TimerTask implements Runnable class
2. Delay time before starting execution
3. Interval time between task execution

2 Timer source code analysis

https://my.oschina.net/wangfushu/blog/1645134

https://blog.csdn.net/u013332124/article/details/79587436

Guess you like

Origin blog.csdn.net/weixin_41477306/article/details/110875352