<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>spring on Shweta Kadam</title>
    <link>https://shwetakadam.com/tags/spring/</link>
    <description>Recent content in spring on Shweta Kadam</description>
    <image>
      <url>https://shwetakadam.com/%3Clink%20or%20path%20of%20image%20for%20opengraph,%20twitter-cards%3E</url>
      <link>https://shwetakadam.com/%3Clink%20or%20path%20of%20image%20for%20opengraph,%20twitter-cards%3E</link>
    </image>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Wed, 12 Jan 2022 23:49:00 +0530</lastBuildDate><atom:link href="https://shwetakadam.com/tags/spring/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Which would you go for? Spring boot cron job,scheduled tasks vs Events in Mysql.</title>
      <link>https://shwetakadam.com/posts/which-would-you-go-for-spring-boot-cron-jobscheduled-tasks-vs-events-in-mysql/</link>
      <pubDate>Wed, 12 Jan 2022 23:49:00 +0530</pubDate>
      
      <guid>https://shwetakadam.com/posts/which-would-you-go-for-spring-boot-cron-jobscheduled-tasks-vs-events-in-mysql/</guid>
      <description>I was recently studying about using cron jobs in spring boot for a particular use case for my small side project. I ended up not using the cron job but rather went the SQL way(will explain this in detail below). However,in the process I learnt a lot about cron jobs and scheduling in spring boot so this is just a small article about my learnings.
But first I shall tell you a little about my use case and why I thought about cron jobs in the first place….</description>
      <content:encoded><![CDATA[<p>I was recently studying about using cron jobs in spring boot for a particular use case for my small side project. I ended up not using the cron job but rather went the SQL way(will explain this in detail below). However,in the process I learnt a lot about cron jobs and scheduling in spring boot so this is just a small article about my learnings.</p>
<p>But first I shall tell you a little about my use case and why I thought about cron jobs in the first place…..</p>
<h2 id="use-case">Use case</h2>
<p>My application was inserting data (let’s call it smash data for simplicity for now)in the database.Each smash data has a certain expiry period and after that expiry period, that data should no longer remain in the database.But the expiry period will be different for each smash data.</p>
<p>Example:</p>
<p>smash 1, expiryperiod :10mins</p>
<p>smash 2 ,expiryperiod :60mins</p>
<p>smash 3 ,expiryperiod :150mins . . . etc.</p>
<p>Now my first line of thinking ended up being cron jobs which led to me studying about cron jobs and scheduled in spring boot.To answer it simply I didn’t end up taking this route is because cron jobs or scheduled tasks are suited when we expect the task to execute at only a particular point of time or where we expect functionality to be executed at w particular time on an hourly/daily /weekly/monthly basis. I could get the cron job to delete the data but to delete WHICH data smash 1 or smash 2? That would mean I would have to check the DB. So the process would be something like:-</p>
<p>Fetch all rows from DB.
Check timestamp of each row data against current timestamp and delete accordingly.
I wanted to avoid writing the searching, comparing time logic (dates, in general, can be a pain sometimes).The logic which I did ended up going through was events in SQL since I’m using MySQL db for the use case</p>
<blockquote>
<p>Mysql events are tasks that run according to a particular schedule …hence they can be called as scheduled events</p>
</blockquote>
<p>When an event is created in MySQL, a named database object is created and this object consists of one or more SQL statements to be executed at some regular intervals.Using events,I didn’t have to retrieve and search the data (as I had to do in the spring boot controller ) . I could just write an event such as</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="line"><span class="cl"><span class="k">Delete</span><span class="w"> </span><span class="k">from</span><span class="w"> </span><span class="n">table1</span><span class="w"> </span><span class="k">where</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w"></span><span class="n">expiry</span><span class="w"> </span><span class="n">period</span><span class="w"> </span><span class="o">&lt;</span><span class="w"> </span><span class="n">NOW</span><span class="p">();</span><span class="w">
</span></span></span></code></pre></div><p>And schedule this to execute <code>every minute</code>. Which was would check for that expiryPeriod column in each row and compare with time NOW() So any rows whose expiryperiod has passed will be deleted from db.</p>
<p>The only thing to note I see in this approach, for now, is that this is database dependent so when I host this side project (a hopeful dream) I need to make sure events is configured for the same. So this was the use case now back to cron jobs!</p>
<h2 id="cron-jobs-or-schedule-tasks-in-spring-boot-dot-permalink">Cron jobs or schedule tasks in spring boot.Permalink</h2>
<p>When a situation arises where we expect the task to execute at only a particular point of time or where we expect functionality to be executed at a particular time on an hourly/daily /weekly/monthly basis. Cron jobs are suitable for this use case. In spring this sort of scheduled task can be achieved through @Scheduled annotation.</p>
<p>There are a few rules while using the @Scheduled annotation:  1. The method should typically have a void return type else the returned value will be ignored.</p>
<p>the method should not expect any parameters. First, to enable scheduling in the spring boot project, use @EnableScheduling in the main class.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">Application</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl"> <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="n">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl"> <span class="n">SpringApplication</span><span class="o">.</span><span class="na">run</span><span class="o">(</span><span class="n">PasteBinApplication</span><span class="o">.</span><span class="na">class</span><span class="o">,</span> <span class="n">args</span><span class="o">);</span>
</span></span><span class="line"><span class="cl"> <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></div><h2 id="scheduling-using-cron-expressions">Scheduling using CRON expressions</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="nd">@Component</span>
</span></span><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SchedulerService</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="nd">@Scheduled</span><span class="o">(</span><span class="n">cron</span><span class="o">=</span><span class="s">&#34;*/15 * * * * ?&#34;</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">testScheduled</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;Method executed at every 15 seconds. Current time is :: &#34;</span><span class="o">+</span> <span class="k">new</span> <span class="n">Date</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></div><p>A guide for cron jobs: cron Image source :Java Techonline
<img loading="lazy" src="/img/cron.PNG" alt=""  />
</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">SEC  MIN   HOURS   DAY  MONTH  WEEKDAY
</span></span><span class="line"><span class="cl"> *    *      *      *     *      *
</span></span></code></pre></div><h2 id="scheduling-using-initial-delay-fixed-delay-or-fixed-rate">Scheduling using initial delay,Fixed Delay or Fixed Rate</h2>
<p>The main difference between Fixed Delay and Fixed Rate is : Fixed Delay : controls the next execution time when the last execution finishes. Fixed Rate : makes Spring run the task on periodic intervals even if the last invocation may be still running.</p>
<p>Fixed Delay</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="nd">@Component</span>
</span></span><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SchedulerService</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="nd">@Scheduled</span><span class="o">(</span><span class="n">fixedDelay</span> <span class="o">=</span> <span class="mi">1000</span><span class="o">,</span> <span class="n">initialDelay</span> <span class="o">=</span> <span class="mi">5000</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">testScheduled</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;Method executed with fixed delay and initial delay . Current time is :: &#34;</span><span class="o">+</span> <span class="k">new</span> <span class="n">Date</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></div><p>Also Fixed Delay can take input in String and Integer. @Scheduled(fixedDelayString = “7000”) @Scheduled(fixedDelayString = 7000)
Fixed Rate:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-java" data-lang="java"><span class="line"><span class="cl"><span class="nd">@Component</span>
</span></span><span class="line"><span class="cl"><span class="kd">public</span> <span class="kd">class</span> <span class="nc">SchedulerService</span> <span class="o">{</span>
</span></span><span class="line"><span class="cl">    <span class="nd">@Scheduled</span><span class="o">(</span><span class="n">fixedRate</span> <span class="o">=</span> <span class="mi">1000</span><span class="o">)</span>
</span></span><span class="line"><span class="cl">    <span class="kd">public</span> <span class="kt">void</span> <span class="nf">testScheduled</span><span class="o">()</span>
</span></span><span class="line"><span class="cl">    <span class="o">{</span>
</span></span><span class="line"><span class="cl">        <span class="n">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="s">&#34;Method executed with fixed rate . Current time is :: &#34;</span><span class="o">+</span> <span class="k">new</span> <span class="n">Date</span><span class="o">());</span>
</span></span><span class="line"><span class="cl">    <span class="o">}</span>
</span></span><span class="line"><span class="cl"><span class="o">}</span>
</span></span></code></pre></div><p>That’s all folks.Learning about events and cron jobs and where could be applied was interesting to learn when applied on some small practical application.</p>
]]></content:encoded>
    </item>
    
  </channel>
</rss>
