How to schedule a Visualforce page using Apex in Salesforce?

How to schedule a Visualforce page using Apex in Salesforce?

Visualforce page:

<apex:page controller="PDFController">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!listEmployees}" var="e">
            <apex:column value="{!e.Name}"/>
            <apex:column value="{!e.Age__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

Apex Controller:

public class PDFController {
    public List<Employee__c> listEmployees {get;set;}
   
    public PDFController() {
        listEmployees = new List<Employee__c>();
        listEmployees = [SELECT Name, Age__c FROM Employee__c];
    }
}

Scheduler Class:

global class EmailSchedule implements Schedulable {
    global void execute(SchedulableContext sc) {
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
        Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
        attach.setContentType('application/pdf');
        attach.setFileName('Employee.pdf');
       
        PageReference Pg = Page.PDFPage;
        Blob body = pg.getcontentAsPdf();

        attach.Body = body;
               
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] { 'your email address' });
        mail.setSubject('PDF Generation');
        mail.setHtmlBody('PFA');
        mail.setFileAttachments(new Messaging.EmailFileAttachment[] { attach });    
       
        mails.add(mail);
       
        if(!mails.isEmpty()) {
            Messaging.SendEmail(mails);
        }
    }
}

Schedule the Scheduler class to receive emails. Kindly use the  below link if you are not aware of scheduling apex classes.
http://www.infallibletechie.com/2012/05/apex-scheduler.html

Leave a Reply