Last active
April 12, 2021 14:18
-
-
Save gbutt/840d9da2db02e687058a05b233d392f1 to your computer and use it in GitHub Desktop.
A way to create schedulable jobs that do not block deployments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
Adapted from the great Dan Appleman. | |
For more on this and many other great patterns - buy his book - http://advancedapex.com/ | |
This class can be used to schedule any scheduled job without risk of locking the class. | |
DO NOT CHANGE THIS CLASS! It is locked by the scheduler. Instead make changes to ScheduledHelper or your own IScheduleDispatched class | |
To use: | |
1) Create a new class to handle your job. This class should implement SchedulableWrapper.IScheduleDispatched | |
2) Create a new instance of SchedulableWrapper with the type of your new class. | |
3) Schedule the SchedulableWrapper instead of directly scheduling your new class. | |
See ScheduledRenewalsHandler for a working example. | |
***/ | |
global class SchedulableWrapper implements Schedulable { | |
public interface I { | |
void setState(Map<String, Object> state); | |
void execute(SchedulableContext sc); | |
} | |
private Type targetType; | |
private Map<String, Object> state; | |
public SchedulableWrapper(Type targetType, Map<String, Object> state) { | |
System.debug('Creating new dispatcher for class: ' + targetType.getName()); | |
this.targetType = targetType; | |
this.state = state; | |
} | |
global void execute(SchedulableContext sc) { | |
I instance = ((I)targetType.newInstance()); | |
instance.setState(state); | |
instance.execute(sc); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IsTest | |
public class SchedulableWrapperTest { | |
@IsTest | |
static void it_should_create_new_instance_of_scheduled_wrappper() { | |
Map<String,Object> testState = new Map<String,Object>{ | |
'executed' => false | |
}; | |
SchedulableWrapper dispatcher = new SchedulableWrapper(TestSchedulable.class, testState); | |
system.assert(dispatcher != null); | |
dispatcher.execute(null); | |
System.assertEquals(true, (Boolean)testState.get('executed')); | |
} | |
public class TestSchedulable implements SchedulableWrapper.I { | |
public Map<String, Object> state {get;set;} | |
public void setState(Map<String, Object> state) { | |
this.state = state; | |
} | |
public void execute(SchedulableContext sc) { | |
if (state != null) { | |
state.put('executed', true); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment