Repeat a task with a time delay?

后端 未结 12 1637
小蘑菇
小蘑菇 2020-11-22 02:14

I have a variable in my code say it is \"status\".

I want to display some text in the application depending on this variable value. This has to be done with a speci

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 02:41

    Based on the above post concerning the ScheduledThreadPoolExecutor, I came up with a utility that suited my needs (wanted to fire a method every 3 seconds):

    class MyActivity {
        private ScheduledThreadPoolExecutor mDialogDaemon;
    
        private void initDebugButtons() {
            Button btnSpawnDialogs = (Button)findViewById(R.id.btn_spawn_dialogs);
            btnSpawnDialogs.setVisibility(View.VISIBLE);
            btnSpawnDialogs.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    spawnDialogs();
                }
            });
        }
    
        private void spawnDialogs() {
            if (mDialogDaemon != null) {
                mDialogDaemon.shutdown();
                mDialogDaemon = null;
            }
            mDialogDaemon = new ScheduledThreadPoolExecutor(1);
            // This process will execute immediately, then execute every 3 seconds.
            mDialogDaemon.scheduleAtFixedRate(new Runnable() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // Do something worthwhile
                        }
                    });
                }
            }, 0L, 3000L, TimeUnit.MILLISECONDS);
        }
    }
    

提交回复
热议问题