List of Sample Cron Expressions To Define Simple And Complex Scheduling

What are Cron Expressions?

Cron-Expressions are used to configure instances of CronTrigger. Cron-Expressions strings are made up of white space separated seven sub-expressions, that describe individual details of the schedule. These seven sub expressions include:

  • Seconds
  • Minutes
  • Hours
  • Day-of-Month
  • Month
  • Day-of-Week
  • Year (optional field)

In job scheduling you will find these expressions very useful. Java programs can be scheduled through Quartz Schedulers. The following are some of the useful cron expressions – some simple, yet some complex  and might be useful for your reference.

  • Cron Expression to fire the trigger every five minutes:
    • 0 0/5 * * * ?
    • (e.g. 3:00:00, 3:05:00, 3:10:00
  • Cron Expression to fire the trigger every hour:
    • 0 0 * * * ?
  • Cron Expression to fire the trigger every two Hours:
    • 0 0 0/2 * * ?
  • Cron expression to fire the trigger every Four Hours:
    • 0 0 0/4 * * ?
  • Cron Expression to fire the trigger every 10 Minutes 20 Seconds:
    • 20 0/10 * * * ?
    • (e.g. 10:00:20, 10:10:20, 10:20:20)
  • Every half an hour between 1 AM to 7 AM on 20th of Every Month
    • 0 0/30 1-7 5, 20 * ?
    • (e.g. 2010-07-20 1:00:00, 2010-07-20 1:30:00m 2010-07-20 2:00:00)
  • Cron Expression to fire the trigger on the 25th Minute from 1 AM to 5 PM on every Monday and Wednesday
    • 0 25 1-5 ? * MON,WED
  • Cron Expression to fire the trigger at Noon every day
    • 0 0 12 * * ?
  • Cron Expression to fire the trigger at Noon every day only in 2010
    • 0 0 12 * * 2010
  • Cron Expression to fire the trigger Every 10 minutes between 9 AM to 5 PM (until 5:50) Every Day
    • 0 0/10 9, 17 * * ?
  • Cron Expression to fire the trigger at 2:30 PM on the last Saturday of every month.
    • 0 30 14 ? * 7L
  • Cron Expression to fire the trigger at 7:10 AM every Monday, Tuesday, Wednesday, Thursday and Friday
    • 0 10 7 ? * MON-FRI
  • Cron Expression to fire the trigger at 2:10 PM and at 2:40 PM every Sunday in the month of July.
    • 0 10,40 14 ? 7 SUN

Peformance Testing Your Java Methods With JUnit and CarrotSearch JUnitBenchmark Tool – With Source Code

I am always in the favor of Test Driven development (TDD), so in addition to following it myself, I always have my developers write a failing test before they begin the coding for any User Story. Once they write the code, we then run the unit test in order to pass them. Folks have a habit of ALWAYS writing unit tests for your code, that will make you a profesional developer.

In this article, I am not going to talk about TDD. But rather I will show you how you can performance test your methods using JUnit and Junit BenchMark tools. The idea behind is, lets say your wrote several methods, and you unit tested those methods using one of the several unit testing methodologies. But how do you make sure it performs well? You know what I mean. You don’t expect your methods to take forever, so unless you measure how much time it takes, you never know. So, I will share my experience with JUnit benchmark tool and show you how easy it is to performance test your individual method.

Unless you already are using these tools (JUnit and JUnit Benchmark Tools), you will need the following two jar files added to the build path of your project.

  1. JUnit Framework Jar File (Visit their site here)
  2. JUnit Benchmark Jar File (visit their site here)

The jar files I am using are junit-benchmarks-0.3.0.jar and junit-4.8.2.2.jar

The following LoopPerformance.java class contains few simple methods. I am not only interested in writing unit tests for those methods, I am also interested to find out if these methods perform well.

package com.kushal.tools.junitbenchmark;

/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 * 
 * Last Modified on: 2012-11-27
 * 
 * This is just a simple class that will be unit and performance
 * tested using JUnit and JUnit Benchmark tool
 */
public class LoopPerformance {

    private final int MAX_ITERATIONS = 100;

    // Do some stuffs in for loop
    public void doForLoop() {

        for (int i = 0; i < MAX_ITERATIONS; i++) {
            /**
             * Some statements. Not intended to have any meanings
             */
            String str = "Hello";
            str += i;
        }
    }

    // Do some stuffs in while loop
    public void doWhileLoop() {

        int i = 0;
        while (i != MAX_ITERATIONS) {
            String str = "Hello";
            str += i;
            i++;
        }
    }

}


The following is a unit test class that I wrote. But it also has some annotations that attach bench marking code to the test.
For example the @Rule annotation is telling the Junit runner to use BenchmarkRule. Although this much is enough to do the performance testing your method using the JUnit test methods, we can further fine tune the test methods with additional annotations.

One example annotation that you can add in from of your unit test method declaration with how many times the methods should run and how many initial warm up rounds are done is:
@BenchmarkOptions(benchmarkRounds = 100000, warmupRounds = 10)

What this means is your test method will be run for 100,010 times but the intial 10 times are considered warm up rounds, so their performance data will not be considered.

Here is another annotation example with parameter to disable garbage collection via callgc parameter.
@BenchmarkOptions(callgc = false, benchmarkRounds = 20, warmupRounds = 3)

package com.kushal.tools.junitbenchmark;

/**
 * @author Kushal Paudyal 
 * www.sanjaal.com/java 
 * www.icodejava.com
 * 
 * Created On: 2012-10-22 
 * Last Modified On: 2012-10-22
 */
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;

import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import com.carrotsearch.junitbenchmarks.BenchmarkRule;

public class JUnitBenchMarkDemoTest {

    // Add a JUnit4 rule that tells JUnit runners to attach benchmarking code to
    // your tests
    @Rule
    public MethodRule benchmarkRun = new BenchmarkRule();

    /**
     * We can fine tune the benchmark with additional 
     * annotated parameters using benchmark options.
     */
    @BenchmarkOptions(benchmarkRounds = 100000, warmupRounds = 10)
    @Test
    public void testDoForLoop() throws Exception {

        LoopPerformance performance = new LoopPerformance();
        performance.doForLoop();
    }

    @BenchmarkOptions(benchmarkRounds = 100000, warmupRounds = 10)
    @Test
    public void testDoWhileLoop() throws Exception {

        LoopPerformance performance = new LoopPerformance();
        performance.doWhileLoop();
    }
}


Here is the output of the performance test run. The output shows what is the total time taken, how many times the test was run for, how much time was spent in garbage collection etc.

JUnitBenchMarkDemoTest.testDoForLoop: [measured 100000 out of 100010 rounds, threads: 1 (sequential)]
 round: 0.00 [+- 0.01], round.gc: 0.00 [+- 0.00], GC.calls: 1503, GC.time: 0.34, time.total: 5.62, time.warmup: 2.85, time.bench: 2.76
JUnitBenchMarkDemoTest.testDoWhileLoop: [measured 100000 out of 100010 rounds, threads: 1 (sequential)]
 round: 0.00 [+- 0.00], round.gc: 0.00 [+- 0.00], GC.calls: 1503, GC.time: 0.35, time.total: 2.54, time.warmup: 0.00, time.bench: 2.54

Please comment on this post (make sure you have registered to my blog), and leave me your feedback.

Tutorial – Encryption And Decryption Using DESede (Triple DES) In Java

We learned how to do a DES Encryption /Decryption in Java in the previous tutorial. In this tutorial, we will extend our knowledge of DES Encryption to DESede also known as Triple DES.

Triple DES is the common name for the Triple Data Encryption Algorithm (TDEA) block cipher.It is so named because it applies the Data Encryption Standard (DES) cipher algorithm three times to each data block. Triple DES provides a relatively simple method of increasing the key size of DES to protect against brute force attacks, without requiring a completely new block cipher algorithm.

The standards define three keying options:

  • Keying option 1: All three keys are independent.
  • Keying option 2: K1 and K2 are independent, and K3 = K1.
  • Keying option 3: All three keys are identical, i.e. K1 = K2 = K3.

Keying option 1 is the strongest, with 3 x 56 = 168 independent key bits.

Keying option 2 provides less security, with 2 x 56 = 112 key bits. This option is stronger than simply DES encrypting twice, e.g. with K1 and K2, because it protects against meet-in-the-middle attacks.

Keying option 3 is no better than DES, with only 56 key bits. This option provides backward compatibility with DES, because the first and second DES operations simply cancel out. It is no longer recommended by the National Institute of Standards and Technology (NIST) and not supported by ISO/IEC 18033-3.

In general Triple DES with three independent keys (keying option 1) has a key length of 168 bits (three 56-bit DES keys), but due to the meet-in-the-middle attack the effective security it provides is only 112 bits. Keying option 2, reduces the key size to 112 bits. However, this option is susceptible to certain chosen-plaintext or known-plaintext attacks and thus it is designated by NIST to have only 80 bits of security. (Information Source: Wikipedia).

The following diagram simplifies the working detail of Triple DES Algorithm.

In the following tutorial, we have used Keying Option 3, where all the keys are identical.

package com.kushal.utils;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESedeEncryption {

	private static final String UNICODE_FORMAT = "UTF8";
	public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
	private KeySpec myKeySpec;
	private SecretKeyFactory mySecretKeyFactory;
	private Cipher cipher;
	byte[] keyAsBytes;
	private String myEncryptionKey;
	private String myEncryptionScheme;
	SecretKey key;

	public DESedeEncryption() throws Exception
	{
		myEncryptionKey = "ThisIsSecretEncryptionKey";
		myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
		keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
		myKeySpec = new DESedeKeySpec(keyAsBytes);
		mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
		cipher = Cipher.getInstance(myEncryptionScheme);
		key = mySecretKeyFactory.generateSecret(myKeySpec);
	}

	/**
	 * Method To Encrypt The String
	 */
	public String encrypt(String unencryptedString) {
		String encryptedString = null;
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
			byte[] encryptedText = cipher.doFinal(plainText);
			BASE64Encoder base64encoder = new BASE64Encoder();
			encryptedString = base64encoder.encode(encryptedText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptedString;
	}
	/**
	 * Method To Decrypt An Ecrypted String
	 */
	public String decrypt(String encryptedString) {
		String decryptedText=null;
		try {
			cipher.init(Cipher.DECRYPT_MODE, key);
			BASE64Decoder base64decoder = new BASE64Decoder();
			byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
			byte[] plainText = cipher.doFinal(encryptedText);
			decryptedText= bytes2String(plainText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptedText;
	}
	/**
	 * Returns String From An Array Of Bytes
	 */
	private static String bytes2String(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i &amp;amp;lt; bytes.length; i++) {
			stringBuffer.append((char) bytes[i]);
		}
		return stringBuffer.toString();
	}

	/**
	 * Testing The DESede Encryption And Decryption Technique
	 */
	public static void main(String args []) throws Exception
	{
		DESedeEncryption myEncryptor= new DESedeEncryption();

		String stringToEncrypt=&amp;quot;Sanjaal.com&amp;quot;;
		String encrypted=myEncryptor.encrypt(stringToEncrypt);
		String decrypted=myEncryptor.decrypt(encrypted);

		System.out.println("String To Encrypt: "+stringToEncrypt);
		System.out.println("Encrypted Value :" + encrypted);
		System.out.println("Decrypted Value :"+decrypted);

	}

}

========================

Here is the sample output:

String To Encrypt: Sanjaal.com
Encrypted Value :aArhqI25Y1SkYrdv9gxYDQ==
Decrypted Value :Sanjaal.com