function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
asadim2asadim2 

System.schedule: cannot catch exception

I have a try/catch block around my System.schedule method (for scheduling) but the UnexpectedException that I keep getting doesn't seem to get caught. I've also tried catching jus the generic Exception but still nothing.

 

Any ideas?

MiddhaMiddha

try catch block does not catch any errors thrown by Salesforce.  Can you post the exact error message you are getting?

asadim2asadim2

System.UnexpectedException: The Apex job named "Test123" is already scheduled for execution.

MiddhaMiddha

You can add a condition to check if the batch job with this name is already scheduled and running. This can be done by querying "CronTrigger " object.

asadim2asadim2

As far as I know the CronTrigger object doesn't have any field containing the schedule name, so I can't do what you just suggestd.

OnkiOnki


Hi,

You can do work around like maintain a custom object which will hold the Id and name of schedule apex.


May be it not recommended by salesforce but as per your business need you can use this way.

 

Step : 1 (when you are scheduling the job first time)

String SCHEDULE_NAME = 'test123';
id cronid = System.schedule(SCHEDULE_NAME, '0 15 0-23 * * ?', new test123());

JobTrack__c Obj = new JobTrack__C();// Custom object will hold the job information
obj.Name = SCHEDULE_NAME;
obj.JobId__C = cronid;
Insert Obj;

Step 2 : when you want delete the job
JobTrack__c obj = [Select Id,JobId__C from JobTrack__c where Name =: 'test123' limit 1];

System.abortJob(obj.JobId__C);

 

Hope it will solve your issue.

 

~Thanks

Onkar