Search code examples
javamysqljavadb

insert data into database after an interval by Java


I need to build a program in java which will insert a data into mysql database after every 10 min.And this will continue as long as the user terminates the program. Do I need Thread to build the program? Please suggest references or a block of code that will invoke automatically after every 10 min.


Solution

  • I would use the java.util.concurrent.* package since it's newer and better for threading (which all timers/delay's will need to implement in order to not block your program)

    This example will execute your task, then re-schedule itself automatically... nice! (the try/finally block ensures no exception will break our schedule):

    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;
    
    class Task implements Runnable {
    
        long untilNextInvocation = 60000; // 1 minute == 60000 milliseconds
    
        private final ScheduledExecutorService service;
    
        public Task(ScheduledExecutorService service) {
    
            this.service = service;
    
        }
    
        @Override
        public void run() {
    
            try {
    
                    // do your stuff here
    
            } finally {
    
                service.schedule(new Task(service), untilNextInvocation, TimeUnit.MILLISECONDS);
    
            }
    
        }
    
    }
    

    UPDATE --

    How to invoke:

    public static void main(String[] args) {
    
        // set 3 available threads
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
    
        // kick off service
        new Task(service).run();
    
    }
    

    OR

    You can invoke it from object constructor:

    public someClassConstructor() {
    
        // set 3 available threads
        ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
    
        // kick off service
        new Task(service).run();
    
    }