Cron Job Prepare Guide

Get a Grasp of Running Methods in Scheduled

Ulaş Müezzinoğlu
5 min readNov 2, 2022

Hello everyone again, in this article I will explain how to run your methods in certain time periods with Scheduled Tasks. To summarize very briefly, we will make their Method run automatically every X hours, X days of the week, and x-y intervals of that day, with very wide range possibilities.

You can find the content of the article below. You can reach the part you want by clicking on it.

What is Scheduled Task ?

I don’t want to repeat the sentence above, but I want to emphasize it in depth. The methods that run automatically according to the time interval given to it by the System without the need for external Developer or User triggering are called Scheduled Task or also known as Cron Job.

Why scheduled task is necessary

One of the main questions asked is, in which scenarios does one need such a thing? I will give some examples and I believe that there will be many more scenarios in your mind.

I would like to give the first example from the scenario I have experienced in my own life :

You have a advertisement system and your users post ads, but these ads last for 30 days. At the end of 30 days, you want to mark the status of the ad as EXPIRED. In this case, the first move that someone who is not familiar with Cron Job will probably do is to add a TTL, Time to Live index to that table. It is obvious from the name that this is a wrong move, we do not want to delete that record at the end of 30 days ! we will only change its status.

So what is the solution?

By preparing a Cron job, you can specify it to run 1 time every day, and inside the method, you can update these entities by pulling the ads that should be expired with a query such as fetch ads over 30 days.

If we give a little more scenario example, you can understand the answer to the question of when you should use it by asking yourself the following question. → If the answer to the question “Do I have to manually trigger this code at x time interval ?” is yes, there is no other reason to use cron job.

Options for Scheduled Task

There are many Schedule Libraries developed as open source in the Community. If we talk a little bit about it: Quartz, Jcrontab, Gos4j and JDRing, but there is no need to think about them, because Spring provide us a great Schedule infrastructure, you can use this structure with just @Scheduled annotation. You can click HERE to see the whole Library list.

Schedule Configuration

Now we can start coding, I need to emphasize a very important point during configuration. Each Job runs itself in a separate thread. and jobs that run too often may cause you to get out of memory error in the future. Therefore, we make Thread Pool Settings during Configuration.

Yes, it’s that simple, you can activate it directly in your project with @EnableScheduling annotation. At the same time, with ThreadPoolTaskScheduler, I set my pool size to 1 and ensured that my jobs run on only 1 thread.

Now let’s prepare a Scheduled Task Method. For now just print a log on the screen.

It worked successfully. and it was executed on only 1 thread, taking into account the Thread Pool exactly as I set it. Now I will give many examples on specifying the time period.

Periodization

@Scheduled annotation can take period in many ways and I will be listing them below.

FixedDelay : It means fixed delay time, Cron Job waits for the time we set in the parameter after the end of the previous job. So when we say fixedDelay=2000, the new job starts 2 seconds after the end of the previous job.

FixedRate : This option is like the previous one but the only difference is that it starts counting time from the start of the previous job. So when we say fixedRate=2000, it means that this job will run 2 seconds after the previous job starts.

small note: the times given in the parameter are in MilliSecond (MS).

Before moving on to the other usage, these 2 usages also have ‘String’ usages.

FixedDelayString | FixedRateString : can take time as String into . for example :

PT1S → Per the 1 second

PT1M → Per the one minute

PT1H → Per the one hour

PT1D → Per the one day

CRON : I wanted to open a separate section for this option because it is different from the others, it is the most advanced and the most different, the different thing is that it takes a CRON EXPRESSION into it.

I am preparing the examples below immediately without confusing you.

Cron expression basically consists of 6 parts. These fields → seconds, minutes, hours, day of the month, month, days of the week

"0 0 * * * *" -> It will work around the clock
"*/10 * * * * *" -> It will run every 10 seconds
"0 0 15-17 * * *" -> It will work every day at 15, 16 and 17 hours
"0 0 15,17 * * *" -> It will work every day at 15 and 17 hours
"0 0 15-17 * * MON-FRI" -> It will work Monday to Friday from 15 to 17 hours

On the code, it will look exactly like this.

@Scheduled(cron = "0 0 15-17 * * *")
public void testSchedule(){
log.info("Test Schedule Runned ! " + Thread.currentThread();
}

Best Practices

There are 2 very useful parameters you can use in the @Scheduled annotation and I would not want to end this article without explaining them.

Time Unit : If you remember, when I was talking about FixedDelay and FixedRate above, I mentioned that they work in MilliSecond. With this parameter you can change the unit of time given.

Zone : As the name suggests, it specifies which zone will work according to the time zone. Yes, we specified in cron as Monday to Friday or 15 to 17, but you can also specify which GMT it is according to.

You can visit my Github Address and Linkedin Profile to support me.

Thanks in advance, Good works.

Sign up to discover human stories that deepen your understanding of the world.

No responses yet

Write a response