In this tutorial, we will show you how to create a scheduler task or cron job on Google App Engine, for Java. In GAE, cron job uses HTTP GET request to call an URL, the duration of the cron job running time is limited to run up to 10 minutes only, if excess, GAE kill your job.

To create a cron job on GAE, just define cron jobs in a file “cron.xml“, and put in the “WEB-INF” folder.

Cron Job Tutorial

Now, we will create a cron job on GAE, and schedule call an URL from Spring MVC REST example.

  1. Google App Engine Java SDK 1.6.3.1
  2. Spring 3.1.1
  3. JDK 1.6
  4. Eclipse 3.7 + Google Plugin for Eclipse

1. Spring Controller

A simple Spring REST controller.

package com.mkyong.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
 
@Controller
@RequestMapping("/cron")
public class CronController {
 
	static int total = 0; 
 
	@RequestMapping(value="/count", method = RequestMethod.GET)
	public String getCount(ModelMap model) {
 
		model.addAttribute("total", total);
 
		return "list";
 
	}
 
        //cron job running this
	@RequestMapping(value="/addCount/{num}", method = RequestMethod.GET)
	public String addCount(@PathVariable int num, ModelMap model) {
 
		total += num; 
		model.addAttribute("total", total);
 
		return "list";
 
	}
 
}

File : list.jsp – Page to display the total counts.

<html>
<body>
	<h1>GAE + Spring 3 MVC REST + CRON Example</h1>
 
	<h3>Counts : ${total} </h3>	
 
</body>
</html>

2. cron.xml

Create a “cron.xml” and put in the “WEB-INF” folder. This cron job will call URL “/cron/addCount/1” every 1 minutes.

File : cron.xml

<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
  <cron>
    <url>/cron/addCount/1</url>
    <description>Add count + 1 every 1 minutes</description>
    <schedule>every 1 minutes</schedule>
  </cron>
</cronentries>
Note
The cron job schedule format is a simple English-like format. Please read this GAE scheduler format for more detail.

every N (hours|mins|minutes) ["from" (time) "to" (time)]

3. Output

Deployed on GAE, you can view the cron job status on application administrator page.

gae cron example

URL : http://mkyong-springmvc-cron.appspot.com/cron/count , result after one minutes

cron job on gae

Download Source Code

Due to large file size, all Spring and GAE jars are excluded.

References

  1. Cron job on GAE for Java
  2. Google App Engine + Spring MVC REST example
Tags :
Founder of Mkyong.com, love Java and open source stuffs. Follow him on Twitter, or befriend him on Facebook or Google Plus.
Here are some of my recommended Books

Related Posts

Popular Posts