0

I have a class, which inserts values in a database (e.g. insertdb.java). But I only want them to be inserted every full hour, so after a little bit of researching and trying different approaches, I tried it with a Thread.sleep. How can I implement this code with the insertdb.java class (not a method)? Thanks in advance for your tips!

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);
        }
     }
xingbin
  • 27,410
  • 9
  • 53
  • 103
pfasch
  • 11
  • 1
  • The `ScheduledExecutorService` is going to call that `run()` method once every hour. So, what's the `sleep()` for? – Solomon Slow Jul 29 '18 at 18:15
  • I thought with `timeunit`, I could let the code run every full hour – pfasch Jul 30 '18 at 07:32
  • OK, but I don't think there is any reason to `sleep()`. The `t.scheduleAtFixedRate(...)` will cause the `run()` method to be called once every hour regardless of whether `run()` sleeps or not. In fact, sleeping for _too_ long actually will slow the thing down because `scheduleAtFixedRate()` will never allow two invocations of the same `Runnable` to execute at the same time. – Solomon Slow Jul 30 '18 at 16:11

1 Answers1

1

You can make class insertdb a member field, and call the insert in run method.

Sample code:

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);
    }
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
  • Thanks so far! But in line 22 it says it cannot make a static reference to the non static field insertdb? What does it mean? – pfasch Jul 29 '18 at 11:23
  • @pfasch You can make it `static` to avoid this, see my updated answer. The explain: https://stackoverflow.com/questions/4969171/cannot-make-a-static-reference-to-the-non-static-method – xingbin Jul 29 '18 at 11:25