0

Lets say I have a main class Start.java

public class Start{
    //Here I want to integrate the programs for which i will be needing threads
}

and I also have two more classes which contains two different methods.

public class ReadUpdateDb {
    public void updateDb(Statement stmt) 
}

public class DbToXls {
    public void dbtoXLS(Statement stmt)
}

Here is my problem: I dont how to assign two different threads to the methods updateDb() and dbtoXLS().

Also, I want to run updateDb after every two hours and dbtoXLS once in a day.

Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
  • 3
    You don't assign different threads to methods; you invoke methods from threads. It looks like you are looking for a `ScheduledExecutorService`, or similar. – Andy Turner Jun 26 '17 at 07:39
  • as Andy suggests. You do not need threads for that. You need some sort of scheduling. I personally use spring boot with it's great task scheduling features to do this without too much boilerplate code. However, a simple timer with scheduled tasks could also suffice. – p.streef Jun 26 '17 at 07:44

2 Answers2

1

As mentioned, ScheduledExecutorService will do the job. I also suggest to name threads using Guava's ThreadFactoryBuilder for example, it will be much easier to debug in the future.

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

import com.google.common.util.concurrent.ThreadFactoryBuilder;

public class Start {

    private static final Integer POOL_SIZE = 2;

    private final ScheduledExecutorService schedExecutor = Executors
                    .newScheduledThreadPool(POOL_SIZE,
                     new ThreadFactoryBuilder().setNameFormat("Schedule-Updater-%d")
                    .setDaemon(true).build());

    public void go() {
        Statement stmt = null;  // construct your statement here
        ReadUpdateDb readUpdateDb = new ReadUpdateDb();
        schedExecutor.scheduleAtFixedRate(() -> readUpdateDb.updateDb(stmt),
                          0, 2, TimeUnit.HOURS);
        DbToXls dbToXls = new DbToXls();
        schedExecutor.scheduleAtFixedRate(() -> dbToXls.dbtoXLS(stmt),
                          0, 1, TimeUnit.DAYS);
        schedExecutor.shutdown();
    }
}

Hope it helps!

Sergey Prokofiev
  • 1,815
  • 1
  • 12
  • 21
  • i tried doing the above but it shows me below error - – Tejas Zambre Jun 26 '17 at 08:59
  • i tried doing the above but it shows me below error in eclipse saying that "Syntax error on token "updateDb", AssignmentOperator expected after this token" at line schedExecutor.scheduleAtFixedRate(readUpdateDb::updateDb, 0, 2, TimeUnit.HOURS); also i forgot to mention that those two methods are take parameters just one readUpdate(Statement stmt) and dbtoXLS(Statement stmt) – Tejas Zambre Jun 26 '17 at 09:06
  • @TejasZambre, "also i forgot to mention that those two methods are take parameters" and that is the case. I've updated answer for you. – Sergey Prokofiev Jun 26 '17 at 09:15
  • No actually i have some oracle queries written in those methods so whenever code starts to execute those queries it comes out of the method and comes back in main so am stuck there. – Tejas Zambre Jun 26 '17 at 15:29
0

You can use ScheduledExecutorService or open source implementation like quartz.

ScheduledExecutorService example for running in every 15 min.

private final ScheduledExecutorService scheduler = Executors
        .newScheduledThreadPool(1);

    public void startScheduleTask() {

    final ScheduledFuture<?> taskHandle = scheduler.scheduleAtFixedRate(
        new Runnable() {
            public void run() {
                try {
                    updateDb();
                }catch(Exception ex) {
                    ex.printStackTrace(); //or loggger would be better
                }
            }
        }, 0, 15, TimeUnit.MINUTES);
    }

QUARTZ Example

public class SimpleTriggerExample {
    public static void main(String[] args) throws Exception {

        // Quartz 1.6.3
        // JobDetail job = new JobDetail();
        // job.setName("dummyJobName");
        // job.setJobClass(HelloJob.class);

        JobDetail job = JobBuilder.newJob(HelloJob.class)
            .withIdentity("dummyJobName", "group1").build();

                //Quartz 1.6.3
        // SimpleTrigger trigger = new SimpleTrigger();
        // trigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
        // trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
        // trigger.setRepeatInterval(30000);

        // Trigger the job to run on the next round minute
        Trigger trigger = TriggerBuilder
            .newTrigger()
            .withIdentity("dummyTriggerName", "group1")
            .withSchedule(
                SimpleScheduleBuilder.simpleSchedule()
                    .withIntervalInSeconds(5).repeatForever())
            .build();

        //job2
        JobDetail job1 = JobBuilder.newJob(HelloJob2.class)
                .withIdentity("dummyJobName1", "group1").build();
        Trigger trigger1 = TriggerBuilder
                .newTrigger()
                .withIdentity("dummyTriggerName1", "group1")
                .withSchedule(
                    SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5).repeatForever())
                .build();
        // schedule it
        Scheduler scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJob(job, trigger);
        //scheduler.scheduleJob(job1, trigger1);

    }
}
gati sahu
  • 2,576
  • 2
  • 10
  • 16