5

I am trying to run an apex class daily using System.schedule but It is not showing up in scheduled jobs nor I am able to query from Cron trigger on owner Id as my Id This is the piece of code. Note : - I need to run my apex class everyday

global class scheduledDeactivation implements Schedulable {
    public static String sch = '0 0 12 1/1 12 ? 2022'; 
    global void execute(SchedulableContext SC) {
      deactivateUsers usrs = new deactivateUsers();
      String jobID = System.schedule('Deactivate Inactive Users', sch, usrs);
      System.debug(jobId);
    }
}
3
  • post the entire class
    – d_k
    Apr 21 '17 at 11:48
  • Do you need apex class as well?
    – Ishan
    Apr 21 '17 at 11:51
  • You seem to have a big misunderstanding about how scheduled jobs work. You don't schedule from within the execute method. That's what's supposed to happen once you hit the scheduled time and actually want to run your logic. You execute the job, or carry out the functionality you intend to run at the ordained time.
    – Adrian Larson
    Apr 21 '17 at 11:53
7

Common Misconception

When you write jobs which implement Batchable or Schedulable, stick with the public modifier. You should never use the global modifier unless you actually need it (webservice functionality or ApexRest) or if you are building a tool which you intend to distribute through a managed package but still want the code to be visible to others.


You don't schedule your job from within the execute method! You should schedule the job from somewhere outside the job. Otherwise every time it runs you add a duplicate job to the queue. The two most common ways to schedule a job which implements the Schedulable interface are:

  1. Through the UI.
    • If you have a simple schedule like every day at X hour, use the UI to schedule.
    • Navigate to Setup > Develop > Apex Classes.
    • Click the Schedule Apex button and select your class/schedule.
    • Click the Save button.
  2. Through a script.
    • If you have a more complicated schedule, you can schedule the job using the system.schedule method.
    • Open up the Developer Console (or your IDE of choice) and go to Execute Anonymous.
    • Fire off a script that calls system.schedule similar to what you are currently attempting in your execute method.
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.