# How to schedule Apex Class using the Date/Time field of an SObject in Salesforce?

In this article, I will explain how can we use the date/time field value of an object record to schedule an apex class in Salesforce.

This can be done by following 6 simple steps as explained below.

### **Create Date/Time Field**

First of all, we will create a Date/Time field on the Contact object as we will be using the Contact object in our apex class. so let's create a date/time field labeled as “**Schedule At”** on the Contact object.

![](https://lh3.googleusercontent.com/GYSPBKYhh2QiYmmpDqGPvSs8vgx_75VFKGeOA3pzEtGHR9boI_YkFa-fBlVZ-q96bRGHnCNG3Sqngz8hWYHnfwexwyJO20Kp2c4JTRXSyo_q6XLgsGB6mdSNsltuECjqGaC7-bWe5I0oe-zAdeQdEDL0zdA8-1VJIN31wilLkWUyRlQ9_bgYHGOrkgJKjg align="center")

### **Create a record**

Next, we will create a sample record for testing purposes. Please make sure while creating the record that you will enter future date-time in the **Schedule At** field. Else you will get an error while scheduling the apex class.

![](https://lh6.googleusercontent.com/_1sqNjMuE9yU1dFRruiKe63pWVOFfJMAs18xKEApqRELt9fgZ_EmjqOYoy0eFaO5JQIQKYAgdwz_l6RQJZQuKq4NKWk-qDnOwjWY1orcNnQFk6YkIJ5a_Px5smsji1dvJdsMTbdYhArtEsoSiMdNveZFrsI85CH2w6e8bQHpVT9_rWuamWzLPi9SOJo5PQ align="left")

### **Write apex code to execute.**

Let us also create a **Scheduled Apex Class**. I have created the class named **ContactSchedule** and added a debug statement for sake of simplicity. You can write the logic you want to execute.

```java
global class ContactSchedule implements Schedulable {
   global void execute(SchedulableContext SC) {
      System.debug('Schedule Run');
   }
}
```

### **Create Cron Expression**

Once you create the scheduled class now is time to write the code for creating **Cron Expression** on the basis of the date-time field value of Contact object.

```java
Contact con=[SELECT Id,Schedule_At__c FROM Contact WHERE Schedule_At__c!=null limit 1]; 
String scheduleDay=String.valueof(con.Schedule_At__c.day());         
String scheduleHour=String.valueof(con.Schedule_At__c.hour());         
String scheduleMinute=String.valueof(con.Schedule_At__c.minute());         
String scheduleMonth=String.valueof(con.Schedule_At__c.month());         
String scheduleYear=String.valueof(con.Schedule_At__c.year());         
String CRON_EXPRESSION = '0 '+scheduleMinute+' '+scheduleHour+' '+scheduleDay+' '+scheduleMonth+' ? '+scheduleYear;                     
System.debug('CRON_EXPRESSION: '+CRON_EXPRESSION);
```

**Note: Replace the Object and Field Name as per your requirement if you are working with another object.**

Above code select a contact record for which the schedule apex should be executed. On the basis of the date-time field, we have created the variables **scheduleDay, scheduleHour, scheduleMinute, scheduleMonth, scheduleYear.** After creating all the variables from the date-time field value we created **CRON\_EXPRESSION** by concatenating all the variables for scheduling the apex.

### **Schedule Apex Class**

Now let's write the code to schedule the apex class. If you have used scheduled apex earlier you already know that we use **system.schedule** method for scheduling the apex class and it accepts 3 parameters which are **Job name, Cron Expression & the class which you want to schedule.**

```java
String jobID = System.schedule('Scheduled from Date Time Field Value', CRON_EXPRESSION, new ContactSchedule()); 
System.debug('Scheduled Job Id: '+jobID);
```

### **Execute code from the anonymous window**

Finally, let's Execute the complete code from the Anonymous window and see the result.

```java
Contact con=[SELECT Id,Schedule_At__c FROM Contact WHERE Schedule_At__c!=null limit 1]; 

String scheduleDay=String.valueof(con.Schedule_At__c.day());         
String scheduleHour=String.valueof(con.Schedule_At__c.hour());         
String scheduleMinute=String.valueof(con.Schedule_At__c.minute());         
String scheduleMonth=String.valueof(con.Schedule_At__c.month());         
String scheduleYear=String.valueof(con.Schedule_At__c.year());  
       
String CRON_EXPRESSION = '0 '+scheduleMinute+' '+scheduleHour+' '+scheduleDay+' '+scheduleMonth+' ? '+scheduleYear;    
                 
System.debug('CRON_EXPRESSION: '+CRON_EXPRESSION);  

String jobID = System.schedule('Scheduled from Date Time Field Value', CRON_EXPRESSION, new ContactSchedule()); 
System.debug('Scheduled Job Id: '+jobID);
```

Once you execute the above code from the anonymous window you will see output like the below image if you have followed exact same steps.

![](https://lh5.googleusercontent.com/tiUN0kJtRNX_7phZag5MYDvi9igTh9mHM1EJdfBwdsjq8isgymaKCrVT1fK5Cxe4AbS3i0KCo09t0MS3EuNdYGVW8VlHWgbOBK1hdCv9y7k9QdqBEdGmd5WsJSGooIj1tUqyZqIvswvkjgufEz96IueT_5d_nsjkLxbfk8K5wPaMGuIlVa9tbJW7E8XD5A align="center")

Also if you want to confirm if the apex class is scheduled or not? Follow the below steps.

1. Go to Setup by clicking on the gear icon.
    
2. Search for Scheduled Jobs.
    
3. You will see a Job with the name **Scheduled from Date Time Field Value** if you have not made any changes while following the above-mentioned steps.
    

![](https://lh4.googleusercontent.com/yuyH9rx5cggaIF_MaTfbXK8kjG6ywaEIuqzG8ipGKRE5fGcy88mO5jTSFIsOp1OtWKcXU65IC4oh5CQJqm_MX14SKC-Wf22o_yMVPqEHrXWIQi_MDb5I4phfZQw2Jj6MPhna2jdELgZBltW-EQEljc0sJniVnI37z_nuCJ4VGLwzmGT31FpZqcJ7lSE9Jw align="center")

That's it you just scheduled the apex class on the basis of the date/time field value of the Contact sobject in Salesforce.

I hope I am able to explain to you **how to schedule an apex class on the basis of date time field value.** If this article helped you then consider buying me a coffee.

I am looking to get into technical writing so if you want me to write an article then please connect with me on my Twitter handle [**here**](https://twitter.com/ShubhamLashkan). Let me also know which topic I should write about next.

Learning Salesforce then do checkout Salesforce Verse: [https://salesforceverse.com](https://salesforceverse.com)
