【问题标题】:How to call method in every minute using Java but in background without affect current process?如何在不影响当前进程的情况下使用 Java 在每分钟调用方法但在后台调用方法?
【发布时间】:2016-02-18 01:32:45
【问题描述】:

程序启动时,后台每分钟自动调用一个方法,不使用线程。

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

【问题讨论】:

标签: java background task


【解决方案1】:

你不能只用 1 个线程同时做 2 件事。您必须创建另一个线程。

【讨论】:

  • 这在 jsp servlet 中是否可行?如果 servlet 或 jsp 正在运行并且在后台执行一个 servlet 而不会影响当前文件。
  • Servlet 正在像 tomcat 这样的容器中初始化。每次调用 servlet 方法时,容器都会在后台为该服务创建一个新线程。我不明白你说它不影响当前文件是什么意思。什么文件?
  • 表示a.jsp或a.java已经在浏览器上运行,所以现在每5分钟b.java文件在后台运行一次,不影响a.jsp或a.java。 a.jsp 文件输出显示在浏览器上,5 分钟后 b.java 文件运行,但用户端仅显示 a.jsp 文件输出。任何在后台运行而不显示用户端的 java 文件或任何用户方法,某些任务可能在后台执行。是否可以使用jsp servlet?
  • 有可能,但要做到这一点,您必须创建另一个线程。您必须创建一个实现 runnable 并覆盖 run 方法的类。在 run 方法中创建一个无限循环并在其中的某处添加 sleep 方法。
【解决方案2】:

假设您需要从 main 每隔 1 分钟调用一次 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
    }
}

【讨论】:

    【解决方案3】:

    您可以使用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);
            }
          }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多