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
vanessa veronvanessa veron 

Code Apex be Schedulable

How do I make my code be Schedulable with the informations that the User inform into Visualforce PAGE?

THE CODE and THE PAGE:

global class CSVTest implements System.Schedulable {
    public String mailSouhaite {get; set;}
    public string inputText {get; set;}
   
    global void execute(SchedulableContext sc) {
        planifier();
    }
 
public void planifier(){
    String query=inputText;
    String premier=query.substringAfter('select ');
    premier=  premier.substringBefore('from');
   
    string titre= premier+'\n';
    string contenuCSV = titre;

    string queryResultatString = '';
    list<sObject> queryResultat = (List<sObject>)database.query(inputText);
    for(sObject a: queryResultat)
    {

        queryResultatString = queryResultatString + string.valueof(a);
    }

    list<string> queryLignes = queryResultatString.split('}');

    for(string s:queryLignes){
        list<string> queryColonnes = s.split(',');
        for(string st:queryColonnes){
            contenuCSV = contenuCSV + st.substringAfter('=') + ',';
        }
        contenuCSV = contenuCSV.substringBeforeLast(',').substringBeforeLast(',') + '\n';
    }
    String lignes = contenuCSV;
    List<String> parts = lignes.split('\n');
    integer lineNumber = queryResultat.size();
    integer nbLignesPJ = 50;
    integer compterParties=0;

    for(integer i=0;i<lineNumber;i++){

      string fichierParties = parts[0] + '\n';

      if(math.mod(i,nbLignesPJ)<>0) continue;
      if((lineNumber-i)<nbLignesPJ){
     
        for(integer j=1;j<=(lineNumber-i);j++){
            fichierParties = fichierParties + parts[i+j] + '\n';
        }
      }
      if((lineNumber-i)>=nbLignesPJ){
         for(integer j=1;j<=nbLignesPJ;j++){
            fichierParties = fichierParties + parts[i+j] + '\n';
        }
      }
      //Send Mail
      Messaging.EmailFileAttachment csvPJ = new Messaging.EmailFileAttachment();
      blob csvBlob = Blob.valueOf(fichierParties);
      string csvNom = 'cases_fermes_'+Date.today().format()+'.csv';
      csvPJ.setFileName(csvNom);
      csvPJ.setBody(csvBlob);
      Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
      String[] adressMail = new list<string> {mailSouhaite};
      compterParties++;
      String subject;
      if (compterParties >=2)
          subject = 'CSV - '+Date.today().format()+' - Partie '+compterParties;
      else
          subject = 'CSV - '+Date.today().format();
      email.setSubject(subject);
      email.setToAddresses(adressMail);
      email.setPlainTextBody('Mail....');
      email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvPJ});
      Messaging.SendEmailResult [] envoyer = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
}

-------------------------------------------------------------------------------------------------------------------------

PAGE

<apex:page controller="CSVTest">
  <apex:form >
  <apex:PageBlock >
    :::::::::: TEST TEST TEST :::::::::: <br /><br />
    Mail..........:&nbsp;<apex:inputText styleClass="classeMail" value="{!mailSouhaite}"/><br /><br />
    Request  :&nbsp;&nbsp;<apex:inputText styleClass="classeRequete" value="{!inputText}"/><br /><br />
    <apex:inputCheckbox id="Monday "/>      
    <apex:outputLabel value="Monday " for="Monday "/><br/>
    <apex:inputCheckbox id="Tuesday "/>      
    <apex:outputLabel value="Tuesday " for="Tuesday "/><br/>
    <apex:inputCheckbox id="Wednesday "/>      
    <apex:outputLabel value="Wednesday " for="Wednesday "/><br/>
    <apex:inputCheckbox id="Thursday "/>      
    <apex:outputLabel value="Thursday " for="Thursday "/><br/>
    <apex:inputCheckbox id="Friday "/>      
    <apex:outputLabel value="Friday " for="Friday "/><br/>
    <apex:inputCheckbox id="Saturday "/>      
    <apex:outputLabel value="Saturday " for="Saturday "/><br/>
    <apex:inputCheckbox id="Sunday"/>      
    <apex:outputLabel value="Sunday" for="Sunday"/><br/><br/>
	
    When:
    <apex:selectList size="1">
         <apex:selectOption itemValue="00:00" itemLabel="00:00"/>
         <apex:selectOption itemValue="01:00" itemLabel="01:00"/>
         <apex:selectOption itemValue="02:00" itemLabel="02:00"/>
         <apex:selectOption itemValue="03:00" itemLabel="03:00"/>
         <apex:selectOption itemValue="04:00" itemLabel="04:00"/>
         <apex:selectOption itemValue="05:00" itemLabel="05:00"/>
         <apex:selectOption itemValue="06:00" itemLabel="06:00"/>
         <apex:selectOption itemValue="07:00" itemLabel="07:00"/>
         <apex:selectOption itemValue="08:00" itemLabel="08:00"/>
         <apex:selectOption itemValue="09:00" itemLabel="09:00"/>
         <apex:selectOption itemValue="10:00" itemLabel="10:00"/>
         <apex:selectOption itemValue="11:00" itemLabel="11:00"/>
         <apex:selectOption itemValue="12:00" itemLabel="12:00"/>
      </apex:selectList>
      <br/><br/>
    
    
    <apex:commandButton value="SEND" action="{!planifier}"/> <br/><br/>
   
  </apex:PageBlock>
  </apex:form>
</apex:page>


Help me please, THANK YOU!


Best Answer chosen by vanessa veron
vanessa veronvanessa veron
I solved the problem
Thank you

<apex:page standardController="CronTrigger" extensions="BBBB">
<style type="text/css">
        .classeHoraire { width: 60px; }
        .classeBig { width: 600px; }
    </style>
	
  <apex:form >
  <apex:PageBlock >
    :::::::::: TEST TEST TEST :::::::::: <br /><br />  
    Mail..........:&nbsp;<apex:inputText styleClass="classeBig" value="{!mail}"/><br /><br />
    Request..:&nbsp;<apex:inputText styleClass="classeBig" value="{!request}"/><br /><br />
    Job Name.......:&nbsp;<apex:inputText value="{!nmJob}"/><br /><br />
        
    Schedule.....:&nbsp;
    <apex:inputText value="{!schedule}" />
    <br /> <br /><br />
	
    <apex:commandButton value="Schedule" action="{!schedulejob}" /> 
  </apex:PageBlock>
  </apex:form>
</apex:page>

--------------------------------------------------------------------------------------------------------------------------------------------------

global class BBBB implements System.Schedulable {

global String mail{get;set;}
global String nmJob{get;set;}
global String request{get;set;}
global String schedule{get;set;}


global void execute(SchedulableContext sc) {
  newPublier();
}

global BBBB () {}


global BBBB (String mail, String request, String schedule) {
this.mail= mail;
this.request= request;
this.schedule= schedule;

}

global void setMail(String mail) {
    this.mail= mail;
}

global String getMail() {
    return mail;
}

global void setRequete(String request) {
    this.request= request;
}

global String getRequete() {
    return request;
}

global void setSchedule(String schedule) {
    this.schedule= schedule;
}

global String getSchedule() {
    return schedule;
}


global void schedulejob(){      
        String email = getMail();
        String req = getRequete();
        String sch = getSchedule();
                       
        String NomJobSchedulable = nmJob;
        BBBB p = new BBBB(email , req, sch);
        system.schedule(NomJobSchedulable , sch, p);
}

public void newPublier(){
    String query=request;
    String premier=query.substringAfter('select ');   
    premier=  premier.substringBefore('from');
      
    string titre= premier+'\n';
    string contenuCSV = titre;

    string queryResultatString = '';
 
    list<sObject> queryResultat = (List<sObject>)database.query(request);
    for(sObject a: queryResultat)
    {
        queryResultatString = queryResultatString + string.valueof(a);  
    }
   
    list<string> queryLignes = queryResultatString.split('}');

    for(string s:queryLignes){
        list<string> queryColonnes = s.split(',');
        for(string st:queryColonnes){
            contenuCSV = contenuCSV + st.substringAfter('=') + ',';
        }
        contenuCSV = contenuCSV.substringBeforeLast(',').substringBeforeLast(',') + '\n';
    }
      }

      Messaging.EmailFileAttachment csvPJ = new Messaging.EmailFileAttachment();
      blob csvBlob = Blob.valueOf(contenuCSV);
      string csvNom = 'cases_fermes_'+Date.today().format()+'.csv';
      csvPJ.setFileName(csvNom);
      csvPJ.setBody(csvBlob);
      Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
      String[] adressMail = new list<string> {mail};
      String subject = 'CSV - '+Date.today().format();
      email.setSubject(subject);
      email.setToAddresses(adressMail);
      email.setPlainTextBody('mail body.........');   
      email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvPJ});
      Messaging.SendEmailResult [] envoyer = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
  }   
}

All Answers

Ashish_SFDCAshish_SFDC
Hi , 


There is no way to pass information in an Apex sense.

Passing Information to Schedulable Job using a Custom Object.

You can pass information via the database, the basic steps are this...

Use the Id returned from the System.schedule method
After scheduling the job insert a record into a Custom Object (e.g. Schedule Info) that contains the information you want the job to read when it executes. Being sure to also store the job Id on the record.
Then in the execute method use the SchedulableContext.getTriggerId (confusing name i know) method to obtain the job Id and query the record previously written for the information needed.
You should consider putting in a try/finally some cleanup code to delete the record once the execute completes.
Apologies for not giving a code sample here, let me know if you need one and I can work one up.

NOTE: You may also want to consider using a List type protected Custom Setting, which has the benifit of saving DML, SOQL and is hidden from the end users.


http://salesforce.stackexchange.com/questions/14634/passing-parameter-into-schedulable-class


Regards,
Ashish
vanessa veronvanessa veron
Uauuu, I'm new in Apex.
There is a simpler way to be done? lol

THANK YOU
Ashish_SFDCAshish_SFDC
Hi Vanessa,


I would suggest you to have some default times fixed and put it in a pick list.

That picklist value can be tracked in SelectOption funtion. 

When the user will select the time avaialble  and save - that will fire the Class in which it will execute the Method written with that particular Cron Expression - you have to validate with the If COndition Loop.

If (Time A ()){

// Cron for time A;

}

Else If (Time B ()) {

// Cron for time B ;

}

Etc..This is a repetative code  but hope this helps.


Regards,
Ashish
vanessa veronvanessa veron
I Will try...

Thank you my friend...
Pramod SharmaPramod Sharma
Storing values in Custom Setting on user actions from Visualforce and retrieving them in Schedulable class will help you here .

Try it !!
vanessa veronvanessa veron
Its dificult, I will try!
Thank you,
vanessa veronvanessa veron
I tested, but I didn't receive the email :

global class CSVTest implements System.Schedulable {
    public String mailSouhaite {get; set;}
    public string inputText {get; set;}
   
    global void execute(SchedulableContext sc) {
        planifier();
    }

 public void CSVTest(){
        planifier();
    }

public void newPlanifier (){
    String dailyCronExpression = '0 0 15 * * ?';
    System.schedule('test', dailyCronExpression, new CSVTest());    
    }
 
public void planifier(){
    String query=inputText;
    String premier=query.substringAfter('select ');
    premier=  premier.substringBefore('from');
   
    string titre= premier+'\n';
    string contenuCSV = titre;

    string queryResultatString = '';
    list<sObject> queryResultat = (List<sObject>)database.query(inputText);
    for(sObject a: queryResultat)
    {

        queryResultatString = queryResultatString + string.valueof(a);
    }

    list<string> queryLignes = queryResultatString.split('}');

    for(string s:queryLignes){
        list<string> queryColonnes = s.split(',');
        for(string st:queryColonnes){
            contenuCSV = contenuCSV + st.substringAfter('=') + ',';
        }
        contenuCSV = contenuCSV.substringBeforeLast(',').substringBeforeLast(',') + '\n';
    }
    String lignes = contenuCSV;
    List<String> parts = lignes.split('\n');
    integer lineNumber = queryResultat.size();
    integer nbLignesPJ = 50;
    integer compterParties=0;

    for(integer i=0;i<lineNumber;i++){

      string fichierParties = parts[0] + '\n';

      if(math.mod(i,nbLignesPJ)<>0) continue;
      if((lineNumber-i)<nbLignesPJ){
     
        for(integer j=1;j<=(lineNumber-i);j++){
            fichierParties = fichierParties + parts[i+j] + '\n';
        }
      }
      if((lineNumber-i)>=nbLignesPJ){
         for(integer j=1;j<=nbLignesPJ;j++){
            fichierParties = fichierParties + parts[i+j] + '\n';
        }
      }
      //Send Mail
      Messaging.EmailFileAttachment csvPJ = new Messaging.EmailFileAttachment();
      blob csvBlob = Blob.valueOf(fichierParties);
      string csvNom = 'cases_fermes_'+Date.today().format()+'.csv';
      csvPJ.setFileName(csvNom);
      csvPJ.setBody(csvBlob);
      Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
      String[] adressMail = new list<string> {mailSouhaite};
      compterParties++;
      String subject;
      if (compterParties >=2)
          subject = 'CSV - '+Date.today().format()+' - Partie '+compterParties;
      else
          subject = 'CSV - '+Date.today().format();
      email.setSubject(subject);
      email.setToAddresses(adressMail);
      email.setPlainTextBody('Mail....');
      email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvPJ});
      Messaging.SendEmailResult [] envoyer = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
}
}

-------------------------------------------------------------------------------------------------------------------------

PAGE

<apex:page controller="CSVTest">
  <apex:form >
  <apex:PageBlock >
    :::::::::: TEST TEST TEST :::::::::: <br /><br />
    Mail..........:&nbsp;<apex:inputText styleClass="classeMail" value="{!mailSouhaite}"/><br /><br />
    Request  :&nbsp;&nbsp;<apex:inputText styleClass="classeRequete" value="{!inputText}"/><br /><br /> 
    <apex:commandButton value="SEND" action="{!newPlanifier}"/> <br/><br/>
   
  </apex:PageBlock>
  </apex:form>
</apex:page>
Help me please!


Shashikant SharmaShashikant Sharma
Hi Venessa,

Although your solution seems right and it may be some other exception that stopped email. Could you enable debug logs and check or may be you could frst est the method "planifier" by changing it in custom button. One it works fine you could change t back to "newPlanifier" .

Let me know if still face issue.
vanessa veronvanessa veron
I solved the problem
Thank you

<apex:page standardController="CronTrigger" extensions="BBBB">
<style type="text/css">
        .classeHoraire { width: 60px; }
        .classeBig { width: 600px; }
    </style>
	
  <apex:form >
  <apex:PageBlock >
    :::::::::: TEST TEST TEST :::::::::: <br /><br />  
    Mail..........:&nbsp;<apex:inputText styleClass="classeBig" value="{!mail}"/><br /><br />
    Request..:&nbsp;<apex:inputText styleClass="classeBig" value="{!request}"/><br /><br />
    Job Name.......:&nbsp;<apex:inputText value="{!nmJob}"/><br /><br />
        
    Schedule.....:&nbsp;
    <apex:inputText value="{!schedule}" />
    <br /> <br /><br />
	
    <apex:commandButton value="Schedule" action="{!schedulejob}" /> 
  </apex:PageBlock>
  </apex:form>
</apex:page>

--------------------------------------------------------------------------------------------------------------------------------------------------

global class BBBB implements System.Schedulable {

global String mail{get;set;}
global String nmJob{get;set;}
global String request{get;set;}
global String schedule{get;set;}


global void execute(SchedulableContext sc) {
  newPublier();
}

global BBBB () {}


global BBBB (String mail, String request, String schedule) {
this.mail= mail;
this.request= request;
this.schedule= schedule;

}

global void setMail(String mail) {
    this.mail= mail;
}

global String getMail() {
    return mail;
}

global void setRequete(String request) {
    this.request= request;
}

global String getRequete() {
    return request;
}

global void setSchedule(String schedule) {
    this.schedule= schedule;
}

global String getSchedule() {
    return schedule;
}


global void schedulejob(){      
        String email = getMail();
        String req = getRequete();
        String sch = getSchedule();
                       
        String NomJobSchedulable = nmJob;
        BBBB p = new BBBB(email , req, sch);
        system.schedule(NomJobSchedulable , sch, p);
}

public void newPublier(){
    String query=request;
    String premier=query.substringAfter('select ');   
    premier=  premier.substringBefore('from');
      
    string titre= premier+'\n';
    string contenuCSV = titre;

    string queryResultatString = '';
 
    list<sObject> queryResultat = (List<sObject>)database.query(request);
    for(sObject a: queryResultat)
    {
        queryResultatString = queryResultatString + string.valueof(a);  
    }
   
    list<string> queryLignes = queryResultatString.split('}');

    for(string s:queryLignes){
        list<string> queryColonnes = s.split(',');
        for(string st:queryColonnes){
            contenuCSV = contenuCSV + st.substringAfter('=') + ',';
        }
        contenuCSV = contenuCSV.substringBeforeLast(',').substringBeforeLast(',') + '\n';
    }
      }

      Messaging.EmailFileAttachment csvPJ = new Messaging.EmailFileAttachment();
      blob csvBlob = Blob.valueOf(contenuCSV);
      string csvNom = 'cases_fermes_'+Date.today().format()+'.csv';
      csvPJ.setFileName(csvNom);
      csvPJ.setBody(csvBlob);
      Messaging.SingleEmailMessage email =new Messaging.SingleEmailMessage();
      String[] adressMail = new list<string> {mail};
      String subject = 'CSV - '+Date.today().format();
      email.setSubject(subject);
      email.setToAddresses(adressMail);
      email.setPlainTextBody('mail body.........');   
      email.setFileAttachments(new Messaging.EmailFileAttachment[]{csvPJ});
      Messaging.SendEmailResult [] envoyer = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
    }
  }   
}

This was selected as the best answer