java - Thread.sleep另一个类

标签 java multithreading scheduled-tasks

我有一个类,它将值插入数据库(例如 insertdb.java)。但我只希望它们每隔一小时插入一次,因此经过一些研究和尝试不同的方法后,我尝试使用 Thread.sleep。如何使用 insertdb.java 类(而不是方法)实现此代码?预先感谢您的提示!

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class thread {
  public static void main(String[] args) {

    ScheduledExecutorService t = Executors.newSingleThreadScheduledExecutor();
    t.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        try {
          Thread.sleep(3600000); }
            catch (Exception e) {}
            }
          }, 0, 1, TimeUnit.HOURS);
        }
     }

最佳答案

您可以将类 insertdb 设为成员字段,并调用 insert in run 方法。

示例代码:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ScheduleTask {

    static Insertdb insertdb;

    public ScheduleTask(Insertdb insertdb) {
        this.insertdb = insertdb;
    }

    public static void main(String[] args) {

        ScheduledExecutorService t = Executors.newSingleThreadScheduledExecutor();
        t.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                try {
                    insertdb.insert();
                    Thread.sleep(3600000);
                } catch (Exception e) {
                }
            }
        }, 0, 1, TimeUnit.HOURS);
    }
}

关于java - Thread.sleep另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51579616/

相关文章:

java - JMenu子菜单鼠标监听没有监听; Action 监听器做了——为什么?

c++ - QEventLoop 用于同步等待信号

powershell - 是否可以使用 powershell 查询所有返回任何上次运行结果不是 (0x0) 的作业的计划任务?

java - 递归实现 CompletableFuture

java - 我在 java.io.PipedInputStream 中发现了错误吗?

java - java/SimpleDateFormat 类中的日期和时间格式/模式

java - 如何在日语 utf-8 汉字上使用 java 子字符串

c++ - 使用 openMP 的并行程序

c++ - VS 2010 中首选的多线程方法/库?

c# - TaskCreationOptions.LongRunning 选项和 ThreadPool