As a developer, I’m a huge fan of code snippets.  If you’ve ever poked around my github account, you might notice this fact from my constantly increasing list of gists.  It really goes beyond that as I have a tendency to keep a couple of Developer Editions around where I can test out code and then if I’m ever needing to remember how to do something specific somewhere else, I’ll just browse through similar code.

While writing some new code for intermediate level features on the platform, it occurred to me that one thing that I never keep track of is how some of that code gets started.  For instance, I might have a trick I used in a trigger somewhere – but except for a crazy simple example, I don’t have a starting template for creating a new trigger.  What I should have in keystroke reach is something like Mike Leach’s Trigger Template from a while back, which not only gives an excellent starting point but also highlights best practices.

So I’m taking steps to rectify that and sharing it with you.  I’m going to start with one of my favorite uses of Apex: running it in the background.  Apex has three basic modes of doing this: being run as a scheduled task, being run in batch, and handling incoming and outgoing emails.  When I’ve used one of these on an org in the past, I’ve noticed I will usually end up using one of the others.  So here is a class which combines all three interfaces in a Github repo I’m calling “nofunc”.  As I create more of these templates, I’ll keep adding them to this org and repo – so that way there will be a project which only has the templates (and no real functionality).

The Asynchronous Apex Template

Let’s break the class down, first the class definition with all the interfaces needed:

global with sharing class AsyncApex implements Database.Batchable<sObject>, Schedulable, Messaging.InboundEmailHandler {
	//To use a callout in batch Apex, you must specify Database.AllowsCallouts
	//   IE: implements Database.Batchable<sObject>, Database.AllowsCallouts{}
	//use Database.Stateful to maintain state between jobs	

	//public or global
	global AsyncApex() {}

Scheduled Apex

Scheduled Apex is fairly straightforward – we just need to version of execute which accepts SchedulableContext.  From there you can either embed all your logic or hand off to a utility class/method.  I prefer the later, mostly because SchedulableContext is not something you can create in Apex – so this is easier to test or operate separately in Developer Console.

	//--- Scheduled Apex
	global void execute(SchedulableContext ctx) {
			//currently SchedulableContext has one method: getTriggerID
			//use System.abort() to stop execution

			//Scheduled logic


Batch Apex

Batch, which refers to code which will loop in the background, is a little more complicated – but remember a lot of tasks can be solves just by setting up the query in start, and then performing DML in execute.  Wash, rinse, and then repeat.  Or rather, that’s how Batchable will see the problem.

	//--- Batch Apex
	global Database.QueryLocator start(Database.BatchableContext BC){
			//similarly, BatchableContext has getJobID method

			//update SOQL for your query locator
			return Database.getQueryLocator('SELECT ID FROM Opportunity WHERE Status__c = \'Closed\' AND CreatedDate < LAST_90_DAYS');

	global void execute(Database.BatchableContext BC, List<sObject> scope) {
			//perform logic and DML
			//upsert scope

	global void finish(Database.BatchableContext BC) {
			//send notifications, final clean up

Email Services / Inbound Email

I’ve always thought the ability to handle inbound emails is one of Apex’s unsung strengths.  It’s very easy to setup, has lots of configuration options under Email Services, and can be incredibly user friendly.  Of course you don’t want to send sensitive information over email, but that doesn’t mean there aren’t a lot of open scenarios where it makes sense.

	//-- Inbound Email
	global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env){
	       //inboundEmail has:
	       //binaryAttachments, textAttachments,
		   //ccAddresses, fromAddress, fromName, replyTo, subject,  toAddresses,
		   //htmlBodyIsTruncated, inReplyTo, messageId, plainTextBody, plainTextBodyIsTruncated, references, headers, htmlBody 

		   //Handle email, ie:
		   //UtilityClass.method(email.Subject, email.plainTextBody);

		   //assuming everything went well
		   Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
	       result.success = true;
	       return result;

And finally, a very simple and generic outbound email function.  This one could be used in several different areas, and I often use outbound emails in conjunction with asynchronous tasks to alert users of what is going on in the background.

	//-- Outbound Email
	static global Boolean sendEmail(String subject, String body, List<String> toAddresses, Boolean isHTML) {
			Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
	        mail.setSubject (subject);
	        if(isHTML) {
			} else {
	        Messaging.SendEmailResult []r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
			return r[0].isSuccess();

So there you have it, a starting point for working with Apex in the background.  If you see changes you’d like to make, or have templates of your own you think might be helpful – branch the nofunc repo off of Github.  Or if you just have requests for upcoming templates, mention them in the comment box below or catch me on twitter @joshbirk.

Here are the doc pages on the specific interfaces:

Get the latest Salesforce Developer blog posts and podcast episodes via Slack or RSS.

Add to Slack Subscribe to RSS