簡體   English   中英

如何在不影響當前進程的情況下使用Java在后台每分鍾調用一次方法?

[英]How to call method in every minute using Java but in background without affect current process?

當程序將啟動時,然后在后台每分鍾自動調用一個方法,而無需使用線程。

class Abc
{
    main()
    {
        do something......
    }
}
class xyz
{
    public void show()
    {
         call every 1 minute in background
         do something.....
         with out affect main method
    }
}

只能使用1個線程一次不能做2件事。 您必須創建另一個線程。

假設您需要每隔1分鍾從main調用一次show()而不干擾main()代碼

class Abc
{
    main()
    {
        Thread mythread = new Thread()
         {
            xyz myClass = new xyz();
            public void run()
            {
              while(true)
              {
                    myClass.show() // this will execute
                    thread.sleep(60000); // this will pause for a bit but wont affect your main code, add this in between try and catch to pause this thread alone withotu affecting main one for 1 min and it goes again and calls show()
               } 
            }
         }
        do something......            
    }
}
class xyz
{
    public void show()
    {
         // whatever you type here will now run every 1 min, without affecting your main code
    }
}

您可以將ScheduledExecutorService用於此任務。

public static class Scheduler {

        private Runnable task;
        private ScheduledExecutorService executorService;

        public Scheduler(Runnable task, ScheduledExecutorService executorService) {
          this.task = task;
          this.executorService = executorService;
        }

        public void start(long startDelay, long period ) {
          executorService.scheduleAtFixedRate(task, startDelay, period, TimeUnit.MINUTES);
        }
      }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM