1

I am working on making a cron job in Java. I want to run a particular task every week, month, three month, six month and nine month.

public Interface interfaceA {
    public String abc() throws Exception;
}

public class TestTaskA implements interfaceA {

    @Override
    public String abc() throws Exception {
        // some code
    }
}

I am running it like this -

TestTaskA testTaskA = new TestTaskA();
testTaskA.abc();    

I want to run TestTaskA every week, every month, every three month, every six month, every nine month and I don't want to run a task between 8 PM till 5 AM. Any random day is also fine.

Now if I am running TestTaskA every week, then it should print out one-week and report_week and if it is running every month, then it should print out one-month and report_one_month. Similarly for three month, six month and nine month.

What is the best way to do this? Keeping in mind, I might have TestTaskB and TestTaskC as well which I am supposed to run every week, month, three month, six month and nine month as well.

Can I use ScheduledExecutorService for this? Any simple example will be of great help to me.

AKIWEB
  • 19,008
  • 67
  • 180
  • 294
  • Have the cron kick off the Java program daily, and have the Java program check the date first thing. Then it can decide if it should run (and what format to use), or not (in which case it can exit). – azurefrog Aug 31 '14 at 22:11
  • I want to build this thing in Java itself instead of using unix cron? – AKIWEB Aug 31 '14 at 22:14
  • @AKIWEB Is there a reason for it to build it in java purely? We have been quite successful with the concept similar to what mittelmania has suggested? – Axel Amthor Aug 31 '14 at 23:35

2 Answers2

1

Quartz scheduler has a very flexible framework to run cron Jobs.

The example below is leveraging Spring.

The first bean initializes the CRON triggers. The second bean is setting the CRON scheduler and finally the third bean is specifying what method in what bean will be executed.

More info is @ http://quartz-scheduler.org/

     <!-- Scheduling  processing via Quartz  -->
    <!-- Step 1. Basically here, you define the list of Triggers, 
here you will define in the list tag 
the weekly,monthly, 3 month etc trigger beans -->

            <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
                <property name="triggers">
                    <list>
                        <ref bean="cronTrigger" />
                    </list>
                </property>
            </bean>



    <!-- Step 2. You define the Trigger. For example this will actually run once every month -->
    <!-- Here you also define what job will be triggered. This trigger will invoke the monthlyJobDetail bean -->

         <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
                <property name="jobDetail" ref="monthlyJobDetail" />
        <!--         run every 2 mins from 9:00 to 17 -->
                <property name="cronExpression" value="0 0 12 1 1/1 ? *"/>
            </bean>



    <!-- Step 3. Define what method in the what bean will be invoked. Here the job defines that targetBean.targetMethod will be invoked. 
         <bean id="monthlyJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
                <property name="targetObject" ref="targetBean" />
                <property name="targetMethod" value="targetMethod" />
                <property name="concurrent" value="false" />
            </bean>

    <!-- Bean that contains buisiness code -->
     <bean id="targetBean" class="com.example.targetBean"/>
Rami Del Toro
  • 1,130
  • 9
  • 24
  • Can you provide an example how would I accomplish this using Quartz? I was more incline towards java util packages class? – AKIWEB Aug 31 '14 at 22:23
  • added a Spring example. Apologies about the format, my browser is kind of flaky at the moment. – Rami Del Toro Aug 31 '14 at 22:36
  • Thanks for the explanation. I got some idea how to use Quartz but is there any way you can provide one simple example for my question so that I get the clear idea how to use Quartz for my question example? Since I never used Quartz so having some problem. :( – AKIWEB Aug 31 '14 at 22:42
0

Since the shortest interval you allow is one week, I recommend that you create a Java class that is fired by cron once a week and checks if there are any tasks to be executed.

Create an abstract class called Task and inherit all the other task classes from it (you may additionally implement any other interface you'd like for each task). Then, when the Java class is launched by cron, iterate over your tasks and determine if it should be executed (using the last time it was executed and its interval, simple math), then execute the task if its time has arrived:

Task.java

public abstract class Task {

    public static enum TaskInterval {
        WEEKLY, MONTHLY, QUARTERLY, SEMI_ANUALLY ,TRI_QUARTERLY
    }

    private long mLastExecutionDate;
    private TaskInterval mInterval;

    public boolean shouldExecute() {
        // Return true if the task should be executed, false otherwise
    }

    public abstract void execute();
}

TaskA.java

public class TaskA extends Task {

    @Override
    public void execute() {
        // Code for TaskA
    }
}

Main.java

public class Main {

    public Main() {
        // Load all the tasks here somehow
        ArrayList<Task> mAllTasks = new ArrayList<Task>();

        for(Task t : mAllTasks) {
            if(t.shouldExecute()) {
                t.execute();
            }
        }
    }
}
mittelmania
  • 3,393
  • 4
  • 23
  • 48