iOS中的NSTimer 和 Android 中的Timer

首先看iOS的,html

Scheduling Timers in Run Loops

A timer object can be registered in only one run loop at a time, although it can be added to multiple run loop modes within that run loop. There are three ways to create a timer:ios

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes the timer (and the strong reference it had to the timer), either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.this


 

總結如下,在ios中,一個timer是和一個runloop密切相關的,用timer,就必須設定它的runloop,否則timer是沒法正常工做的。另一個timer invalid以後,就沒法再次啓用,必須新建timer。spa

在iOS中,如不採用特殊設置,在應用程序進入後臺後,與應用程序相關的線程當即暫停,天然在thread中執行的timer也會中止運行。當應用程序再次進入前臺時,暫停的thread會被恢復。線程

另外須要注意,看下代碼code

 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT , 0), ^{
        NSLog(@"async....");
        NSRunLoop *runloop = [NSRunLoop currentRunLoop];


        timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(test) userInfo:nil repeats:YES];

        [runloop addTimer:timer forMode:NSRunLoopCommonModes];
     //注意順序,先加入源,再用run方法!
        [runloop run];


    });

新線程若是想啓動runloop,不能單單寫[runloop run],必須先加入一個觸發源,好比這裏的timer,否則runloop運行run方法後會當即返回,什麼做用都沒有。htm


 

在Android中,

Timer 在使用時自動開啓新線程,好比如下代碼

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_log_in);

     System.out.println("Thread.currentThread()....."+Thread.currentThread().getId())  ;

        TimerTask task = new TimerTask() {
            public void run() {
                //每次須要執行的代碼放到這裏面。
                System.out.println("Thread.currentThread()"+Thread.currentThread().getId())  ;
                System.out.println(".........TimerTask.........run");

            }
        };



        Timer timer = new Timer();
        timer.schedule(task,1000,1000);
}

如下是輸出

Thread.currentThread().....1
Thread.currentThread()319
Thread.currentThread()319

從這裏咱們能夠看出,Android中的timer是自動建立新線程並運行的,主線程的阻塞不會影響定時器的運行。

當程序進入後臺後,程序的全部線程都不會中止,直到該線程被系統或代碼中止。

相關文章
相關標籤/搜索