Scheduled class not showing up in scheduled jobs
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 users = new deactivateUsers(); String jobID = System.schedule('Deactivate Inactive Users', sch, usrs); System.debug(jobId); } }
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 (web service 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:
Through the UI.
- If you have a simple schedule like every day at X hour, use the UI to schedule class.
- Navigate to Setup > Develop > Apex Classes.
- Click the Schedule Apexbutton and select your class/schedule.
- Click the Save button.
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.