Wednesday, 9 August 2017

Salesforce Trailhead : Process Automation Super Badge


Challenge 1:

Validation rule on Lead

Country Validation Rule

Condition Formula: NOT( 
OR(
Country = "US",
Country = "USA",
ISBLANK( Country )
)
)

Error Location: Field Country

State Validation Rule

Condition Formula: OR( 
LEN(State) <> 2,
NOT(CONTAINS("AL:AK:AZ:AR:CA:CO:CT:DE:DC:FL:GA:HI:ID:" &
"IL:IN:IA:KS:KY:LA:ME:MD:MA:MI:MN:MS:MO:MT:NE:NV:NH:" &
"NJ:NM:NY:NC:ND:OH:OK:OR:PA:RI:SC:SD:TN:TX:UT:VT:VA:" &
"WA:WV:WI:WY:PR", State))
)
Error Location: Field State

Queues:

Queue Name: Rainbow Sales

Queue Name: Assembly System Sales

Assignment Rule:

Rule Name: Trailhead Assigment Rule

Challenge 2:

Account Validation Rules

Billing Country Rule


Shipping Country Rule

Billing State Rule


Shipping State Rule


Account Name Rule

Account Fields:


  • Number of deals (Roll-Up Summary field): Count Opportunity. No filter criteria
  • Number of won deals (Roll-Up Summary field): Count Opportunity with filter criteria as "Stage equals Closed Won"
  • Last won deal date (Roll-Up Summary field): MAX(Opportunity: Close Date) with filter criteria as "Stage equals Closed Won"
  • Deal win % (Formula field): Number_of_won_deals__c / Number_of_deals__c
  • Total amount of won deals (Roll-Up Summary field): SUM(Opportunity: Amount) with filter criteria as "Stage equals Closed Won"
  • Call for Service (Formula field): IF( DATE( YEAR(Last_won_deal_date__c)+2 , MONTH(Last_won_deal_date__c) , DAY(Last_won_deal_date__c) ) <= TODAY(), 'Yes', 'No')

Challenge 3:

Custom Object Creation



Challenge 4:

Add Stage Value:


Add Custom Field:


Add Sales Process:


Add Recordtype

Validation Rule

Challenge 5:

Approval Process:


Note: Make sure you populate manager field on your user record with some valid user. In this case make your manager as Naushi(User you created in your org). If you wont select user manager you wont be able to submit for approval.

Email Alert


Note: Make sure you add a user in email alert

Process Builder:

Opportunity object with option created and updated.

1st and 2nd node end will be changed to evaluate next criteria.



1st Node Criteria

Opportunity Account Type = customer and opportunity.account id not equal to null

1st Node Action

2nd Node Criteria

Opportunity stage = prospecting and opportunity.account id not equal to null and opportunity account type = Prospect.


Note: there will be 2 actions 1 is email same as above and second is creating task. 

2nd Node Action:


3rd Node Action:

Opportunity Stage = Negotiation/Review

3rd Node Action:

4th Node Criteria:

Opportunity Stage = Closed Won

4th Node Action:

2 actions are used in this node.


Challenge 6:

Flow:


  • Flow must be of type Flow. 
  • Screen with 3 choices and store the result in screen choice fields : ProductType
  • Lookup to find records in product2 with contains ProductType and store them as variables (Id + name) 
  • Screen to display variables 
  • Activate the flow 
  • Add the flow to the opportunity screen using app builder.








Lightning Page:

A record page on Opportunity object. 
Drag and drop flow component on it and save.
Activate page.


Challenge 7

  • Change field type of field "Day of the Week" on robot object to formula text and use below formula.
  • CASE( MOD( Date__c - DATE(1900,1,6),7) , 0, "Saturday",1,"Sunday",2,"Monday",3,"Tuesday",4,"Wednesday",5,"Thursday",6,"Friday","")
  • Go on Process builder created in step 5.(You have to clone this Process Builder in order to make changes)
  • Go on 4th Node of closed Won opportunity.
  • Go on action create setup record.
  • Change formula of date field from [Opportunity].CloseDate + 180..
  • to
  • CASE(MOD([Opportunity].CloseDate + 180 - DATE(1900, 1, 7),7), 0, [Opportunity].CloseDate + 181, 6, [Opportunity].CloseDate + 182, [Opportunity].CloseDate + 180)
  • Save and activate.
Happy Coding!!!

Monday, 5 June 2017

Dell Boomi: Read all repeating tags text and put in one text field using groovy

Read data of all repeating tags and put in one text field

If you are working with Dell Boomi in order to integrate SAP data you must find a need for this, as this is SAP standard behavior that when it creates an XML or IDoc of text data it start reapeating tags till the number of enter in that field.

E.g:
In SAP you enter following text:
This is my first blog
I am writing this blog about Dell Boomi
and SAP general behaviors

When an IDoc/XML file will be created it will look like this:
<IDOC BEGIN="1">
<Notes>This is my first blog</Notes>
<Notes> I am writing this blog about Dell Boomi </Notes>
<Notes> and SAP general behaviors </Notes>
</IDOC BEGIN="1">

Problem
Now issue is that your destination system need this complete text in one field along with enters. If you directly map this tag in your map component only Dell Boomi will only read first ever line and all the other text will be gone.

Solution
In order to solve this issue you can use groovy in data process to read all these kind of repeating tags and then create a new node in your process and map that node with your destination text field.

Groovy Code: 
import java.util.Properties;
import java.io.InputStream;
import org.jdom.input.SAXBuilder;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.xpath.XPath;
import org.jdom.output.XMLOutputter;
import com.boomi.execution.ExecutionUtil;

Integer Count = 0;
for( int i = 0; i < dataContext.getDataCount(); i++ ) {

 InputStream is = dataContext.getStream(i);
 Properties props = dataContext.getProperties(i);
   
 // Build XML Document
 SAXBuilder builder = new SAXBuilder();
 Document doc = builder.build(is);

 XPath Approved_Pricing;
 Approved_Pricing = XPath.newInstance("//ZDEBMAS/IDOC/E1KNVVH[TDID='Z002']/E1KNVVL/TDLINE");
 
 MSGFN = Approved_Pricing.selectNodes(doc);
 
 Desc='';
 result = new StringBuffer();
for(int ak=0;ak<MSGFN.size();ak++){
if (Count < 10){
result.append(MSGFN[ak].getText()+System.getProperty('line.separator'));
Count = Count + 1;
}
}
    Desc = result.toString();
Notes = new Element("Pricing_Notes_Description").addContent(Desc);
x = XPath.newInstance("//ZDEBMAS/IDOC");
    eleParentElement = x.selectSingleNode(doc);
    if(eleParentElement !=null){
      eleParentElement.addContent(Notes);
    }
     XMLOutputter outputter = new XMLOutputter();
     is = new ByteArrayInputStream(outputter.outputString(doc).getBytes("UTF-8"));

     dataContext.storeStream(is, props);
}

You are adding a new element Notes in the root IDoc which you can then map to your destination field.you also have to provide complete and accurate path of that repeating tag.


Hope this helps you. Happy Coding !!!

Wednesday, 31 May 2017

Dell Boomi: Update Flat File/CSV data using groovy script

Update data of CSV file using Groovy

In this blog i am trying to share my experience of updating csv data using groovy scripts. I had an explicit requirement that i have to remove leading zeros from a integrer data field before passing it to my map.

As you all work on Dell Boomi so you know that in Boomi there are so many built in Strings function which can do this task very easily or you can use a simple javascript code to achieve this functionality.

Javascript code:

Output = Input.replace(/^0+/, '') ;


I have to do this by groovy because in the data process you can only use groovy script and i have to remove leading zeros before passing it to map function.

Sample file:

test-trstevens113@msn.com,Test User,0000100098,8797784047620,trstevenstest@msn.com,,,0,2016-01-18 11:36:32.847,0000123652
test-tstevens@lves.washk12.org,Test2 User,0000100098,87976289823652,tstevens222@lves.washk12.org,,,0,2016-01-18 11:35:45.327,000012352


Note:
I have to remove leading zeros from column 3 that is "0000100098" but in code below i use 2 as this is indexed with zero.

Code of Groovy:

import java.util.Properties;
import java.io.InputStream;
import java.io.BufferedReader;


String DELIMITER = ",";

for( int i = 0; i < dataContext.getDataCount(); i++ ) {

   InputStream is = dataContext.getStream(i);
   Properties props = dataContext.getProperties(i);

   BufferedReader reader = new BufferedReader(new InputStreamReader(is));
   StringBuffer outData = new StringBuffer();
   int lineNum = 0;
      
   while ((line = reader.readLine()) != null) {
// Parse the line into separate columns splitting on the delimiter defined above
String[] columns = line.split(DELIMITER);

         // Obtain a column's value by its known position on the line (zero-indexed)
String someColumnValue = columns[2];

columns[2] = someColumnValue.replaceFirst("^0+(?!\$)", "");
for(int k = 0; k < columns.length; k++){
outData = outData.append(columns[k]+DELIMITER);

//outData.append('\n');
}
    
      lineNum++;
   }
   
   // Convert the output StringBuffer to an InputStream and store in the dataContext
   is = new ByteArrayInputStream(outData.toString().getBytes("UTF-8"));
   dataContext.storeStream(is, props);
   
}

Hope this helps you. Happy Coding !!!

Friday, 26 May 2017

Apex: Dynamic Scheduling of batch job for quarters from VF page

Schedule Batch job for Quarters from Visualforce Page:

Few days back i get chance to work for a client requirement to give ability to schedule a batch job quarterly from a visualforce page. As you all know that you can not even schedule a batch job quarterly from salesforce UI.


In order to schedule a job on quarterly manner I have to first calculate the dates and time input by your user. I am illustrating my requirements here with screen shots.
  • A picklist to select frequency
  • A picklist to select date option
  • A picklist to select date operator
  • A text box to enter  number of days
  • A picklist for start time




Controller Class Code:


  • First of all calculate first/end of quarter

/************************************GetFirstOfQuarterMonth****************************/
    public Integer GetFirstOfQuarterMonth(){
       
        if(date.today().month() ==1 || date.today().month() ==2 || date.today().month() ==3)
            return 1;
        else if(date.today().month() ==4 ||date.today().month() ==5 || date.today().month() ==6)
            return 4;
        else if(date.today().month() ==7 || date.today().month() ==8 || date.today().month() ==9)
            return 7;
        else
            return 10;
    }
/************************************GetEndOfQuarterMonth****************************/
    public Integer GetEndOfQuarterMonth(){
       
        if(date.today().month() ==1 || date.today().month() ==2 || date.today().month() ==3)
            return 3;
        else if(date.today().month() ==4 ||date.today().month() ==5 || date.today().month() ==6)
            return 6;
        else if(date.today().month() ==7 || date.today().month() ==8 || date.today().month() ==9)
            return 9;
        else
            return 12;
    }


  • Validate Frequency Number


/****************IsValidFrequencyNo***************************/
    public Boolean IsValidFrequencyNo(String Value){
        Boolean flag = false;
        if(Value != null) {
            String CalRegex = '^(?:[1-9]{1}|4[0-6]|2[0-9]|3[0-9]|1[0-9])$';
            Pattern CalPattern    = Pattern.compile(CalRegex);
            Matcher CalMatcher    = CalPattern.matcher(Value.trim());
            flag                    =  CalMatcher.matches();
        }
        return flag;
    }

  • Calculate Cron string

if(SelectedRenewalFrequency == Constants.QUARTERLY){
            String QuarterDate = '';
            
            if(SelectedRenewalFreqDatePeriod == Constants.FIRSTOFQUARTER_VALUE){
                
                if(!String.IsBlank(SelectedRenewalFreqValue) && !String.IsBlank(SelectedRenewalFreqDateOperator)){
                    Integer FOQMonth = GetFirstOfQuarterMonth();//Getting quarter month
                    date startOfQuarter=Date.valueof(Date.today().year()+'-' + FOQMonth +'-1');//Getting start of quarter
                    String AllMonth = '';
                    if(SelectedRenewalFreqDateOperator == Constants.PLUS){
                        if(startOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)) < date.today())
                    startOfQuarter = date.valueOf(startOfQuarter.addMonths(3));
                        QuarterDate = string.valueOf(startOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)).day());
                        Integer MonthNo = Integer.valueOf(startOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)).month()) - FOQMonth;
                        Integer TwelvethMonth = 10+MonthNo; 
                        if(TwelvethMonth >12)
                            TwelvethMonth = MonthNo;
                        AllMonth = String.valueOf(1+MonthNo)+','+String.valueOf(4+MonthNo)+','+String.valueOf(7+MonthNo)+','+String.valueOf(TwelvethMonth);
                    }
                    else{
                    if(startOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)) < date.today())
                    startOfQuarter = date.valueOf(startOfQuarter.addMonths(3));
                        QuarterDate = string.valueOf(startOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)).day());
                        Integer MonthNo = Integer.valueOf(startOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)).month()) - FOQMonth;
                        Integer FirstMonth = 1+MonthNo;
                        if(FirstMonth == 0)
                        FirstMonth = 12;
                        if(String.valueOf(FirstMonth).contains('-')){
                            if(FirstMonth == -1)
                                FirstMonth = 12;
                            else
                                FirstMonth = 11;
                        }
                        Integer TwelvethMonth = 10+MonthNo; 
                        if(TwelvethMonth >12)
                            TwelvethMonth = MonthNo;
                        AllMonth = String.valueOf(FirstMonth)+','+String.valueOf(4+MonthNo)+','+String.valueOf(7+MonthNo)+','+String.valueOf(TwelvethMonth);
                        if(FirstMonth == 12)
                        AllMonth = String.valueOf(4+MonthNo)+','+String.valueOf(7+MonthNo)+','+String.valueOf(TwelvethMonth)+ ','+String.valueOf(FirstMonth);
                    }
                    sch = '0 0 '+ Schdtime+ ' ' + QuarterDate + ' '+ AllMonth + ' ? *';
                }
                else
                    sch = '0 0 ' + Schdtime + ' 1 1,4,7,10 ? *';
            }
            else{
                if(!String.IsBlank(SelectedRenewalFreqValue)&& !String.IsBlank(SelectedRenewalFreqDateOperator)){
                    Integer EOQMonth = GetEndOfQuarterMonth();//Getting quarter month
                    //Getting start of quarter
                    date endOfQuarter=Date.valueof(Date.today().year()+'-' + EOQMonth +'-' + Date.daysInMonth(Date.today().year(), EOQMonth) );
                    if(SelectedRenewalFreqDateOperator == Constants.PLUS){
                    if(endOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)) < date.today())
                    endOfQuarter = date.valueOf(endOfQuarter.addMonths(3));
                        QuarterDate = string.valueOf(endOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)).day());
                        Integer MonthNo = Integer.valueOf(endOfQuarter.adddays(integer.valueOf(SelectedRenewalFreqValue)).month()) - EOQMonth;
                        Integer TwelvethMonth = 12+MonthNo; 
                        if(TwelvethMonth >12)
                            TwelvethMonth = MonthNo;
                        String AllMonth = String.valueOf(3+MonthNo)+','+String.valueOf(6+MonthNo)+','+String.valueOf(9+MonthNo)+','+String.valueOf(TwelvethMonth);
                        sch = '0 0 '+ Schdtime+ ' ' + QuarterDate + ' '+ AllMonth + ' ? *';
                    }
                    else{
                    if(endOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)) < date.today())
                    endOfQuarter = date.valueOf(endOfQuarter.addMonths(3));
                        Integer MonthNo = Integer.valueOf(endOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)).month()) - EOQMonth;
                        Integer TwelvethMonth = 12+MonthNo; 
                        if(TwelvethMonth >12)
                            TwelvethMonth = MonthNo;
                        String AllMonth = String.valueOf(3+MonthNo)+','+String.valueOf(6+MonthNo)+','+String.valueOf(9+MonthNo)+','+String.valueOf(TwelvethMonth);
                        QuarterDate = string.valueOf(endOfQuarter.adddays(integer.valueOf('-'+SelectedRenewalFreqValue)).day());
                        sch = '0 0 '+ Schdtime+ ' ' + QuarterDate + ' '+ AllMonth + ' ? *';
                    }
                }
                else{
                    sch = '0 0 '+ Schdtime +' 30 6,9 ? *';
                    
                }
            }
        }

  • Schedule job
public string JobSchedular(){
string sch = GetCronStringForSchedule();
      string  jobID = system.schedule(BATCH_JOB_NAME, sch, batchjob);
return jobID;
}

Note: Constants is a separate class i have created to keep all my constants at one place and can be used in all classes.

VF page Code:

<apex:selectList label="Date Option" multiselect="false" size="1" id="RenewalFrequencyQuartely" value="{!SelectedRenewalFreqDatePeriod}"
                    rendered="{!IF(SelectedRenewalFrequency == 'Quarterly',true,false)}" disabled="{!IsDisabled}">
                    <apex:selectOptions value="{!FrequencyDatePeriod}"/>
                       <apex:actionSupport event="onchange"  action="{!RenewalFrequencyDatePeriodOnChange}" reRender="pbs10" status="theStatus"/>
                </apex:selectList>
                
                <apex:selectList label="Date Operator" multiselect="false" size="1" id="RenewalFrequencyDateOperator"  value="{!SelectedRenewalFreqDateOperator}"
                    rendered="{!IF(SelectedRenewalFrequency == 'Quarterly',true,false)}" disabled="{!IsDisabled}">
                    <apex:selectOptions value="{!DateOperator}"/>
                </apex:selectList>
                
                <apex:selectList label="Day Of Month" multiselect="false" size="1" id="RenewalFrequencyDayOfMonth"  value="{!SelectedRenewalFreqValue}"
                    rendered="{!IF(SelectedRenewalFrequency == 'Monthly',true,false)}" disabled="{!IsDisabled}">
                    <apex:selectOptions value="{!ListNoOfDayInMonth}"/>
                </apex:selectList>
                
                <apex:inputText label="No. of Days" value="{!SelectedRenewalFreqValue}" id="RenewalFreqMonthly" title="Date can be any value"
                    rendered="{!IF(SelectedRenewalFrequency == 'Quarterly',true,false)}" disabled="{!IsDisabled}"/>
                
                
                <apex:selectList label="Time" multiselect="false" size="1" id="RenewalTime" 
                    value="{!SelectedRenewalTime}" disabled="{!IsDisabled}">
                    <apex:selectOptions value="{!FrequencyTime}"/>
                </apex:selectList>

Hope this helps you. Happy Coding !!!

Thursday, 31 March 2016

Apex: Creating CRON Expression dynamically from VF page

CRON Expression:

A command to an operating system or server for a job that is to be executed at a specified time.

CRONTrigger:

An object that contains schedule information for a schedule job.This object contain all the information related to any schedule job in your organization. Read More Here!

Visualforce Page for Dynamic CRON Creation:

The use case this page covers is when users want to schedule  a class from VF page.User have choice to set schedule date and time according to his convenience from any day of week.

We will be using Multiselect picklist to show days of weeks as user might want to schedule it for more than 1 day.



We will use single select picklist in order to capture preferred time from user.


VF Page Code:

     <apex:pageBlock id="pb4">
            <apex:pageBlockSection title="Frequency" id="pbs10" collapsible="false" 
             columns="1">
            
                <apex:selectList label="Recurs Every Week On" multiselect="true"  
                 size="5" id="FrequencyWeekly" value="{!SelectedFreqValue}">
                    <apex:selectOptions value="{!OppWeekDays}"  />
                       
                </apex:selectList>
               
                <apex:selectList label="Preferred Start Time" multiselect="false"  
                 size="1" id="Time" value="{!SelectedTime}">

                    <apex:selectOptions value="{!FrequencyTime}"/>
                </apex:selectList>
                    
                <apex:outputLabel styleclass="labelCol vfLabelColTextWrap" 
                 value="Exact time will be dependent on Job queue activity" 
                 style="text-align:left !important; font-size: 10px !important;"/>
            </apex:pageBlockSection>
            
        </apex:pageBlock>

Controller Class Code

//Defining Properties for capturing Frequency
    public String SelectedFreqValue {get;set;} 
    public string SelectedTime {get;set;}

//Defining List of selectoption
public List<selectOption> OppWeekDays{get;set;}
 public List<selectoption> FrequencyTime{get;set;}

/****************************************************getFrequencyTime**********************************/
    //get frequency time
    public List<selectOption> getFrequencyTime(){
        
        FrequencyTime = new List<selectoption>();
        
        FrequencyTime.add(new selectOption('0',Constants.CONST_TWELVE_AM));
        FrequencyTime.add(new selectOption('1',Constants.CONST_ONE_AM));
        FrequencyTime.add(new selectOption('2',Constants.CONST_TWO_AM));
        FrequencyTime.add(new selectOption('3',Constants.CONST_THREE_AM));
        FrequencyTime.add(new selectOption('4',Constants.CONST_FOUR_AM));
        FrequencyTime.add(new selectOption('5',Constants.CONST_FIVE_AM));
        FrequencyTime.add(new selectOption('6',Constants.CONST_SIX_AM));
        FrequencyTime.add(new selectOption('7',Constants.CONST_SEVEN_AM));
        FrequencyTime.add(new selectOption('8',Constants.CONST_EIGHT_AM));
        FrequencyTime.add(new selectOption('9',Constants.CONST_NINE_AM));
        FrequencyTime.add(new selectOption('10',Constants.CONST_TEN_AM));
        FrequencyTime.add(new selectOption('11',Constants.CONST_ELEVEN_AM));
        FrequencyTime.add(new selectOption('12',Constants.CONST_TWELVE_PM));
        FrequencyTime.add(new selectOption('13',Constants.CONST_ONE_PM));
        FrequencyTime.add(new selectOption('14',Constants.CONST_TWO_PM));
        FrequencyTime.add(new selectOption('15',Constants.CONST_THREE_PM));
        FrequencyTime.add(new selectOption('16',Constants.CONST_FOUR_PM));
        FrequencyTime.add(new selectOption('17',Constants.CONST_FIVE_PM));
        FrequencyTime.add(new selectOption('18',Constants.CONST_SIX_PM));
        FrequencyTime.add(new selectOption('19',Constants.CONST_SEVEN_PM));
        FrequencyTime.add(new selectOption('20',Constants.CONST_EIGHT_PM));
        FrequencyTime.add(new selectOption('21',Constants.CONST_NINE_PM));
        FrequencyTime.add(new selectOption('22',Constants.CONST_TEN_PM));
        FrequencyTime.add(new selectOption('23',Constants.CONST_ELVEN_PM));
        
        return FrequencyTime;
    }


/*************************************************getOppWeekDays****************************************/
    //get renewal opp week days list
    public List<SelectOption> getOppWeekDays(){
        
        OppWeekDays = new List<selectoption>();
        
        OppWeekDays.add(new selectOption('SUN',CONST_SUNDAY));
        OppWeekDays.add(new selectOption('MON',CONST_MONDAY));
        OppWeekDays.add(new selectOption('TUES',CONST_TUESDAY));
        OppWeekDays.add(new selectOption('WED',CONST_WEDNESDAY));
        OppWeekDays.add(new selectOption('THUR',CONST_THURSDAY));
        OppWeekDays.add(new selectOption('FRI',CONST_FRIDAY));
        OppWeekDays.add(new selectOption('SAT',CONST_SATURDAY));
        
        return OppWeekDays;
    }

Create a constant class where you can add all times you want to show on page.Like i create a 
class name "Constant" and add times from "12 AM" till "11 PM" and names of days from Sunday till Saturday.


CRON Creation Method


public string GetCronStringForSchedule(){
        Integer Schdtime = Integer.valueOf(SelectedTime);
         string sch = '';
            string a = '';
            SelectedFreqValue= SelectedFreqValue.replaceAll( '\\s+', '');
            SelectedFreqValue = SelectedFreqValue.remove(')');
            SelectedFreqValue = SelectedFreqValue.remove('(');
            List<String> ListOfValues = SelectedFreqValue.split('\\,');
            if(ListOfValues.size() >0)
                a = ListOfValues.get(0)+ '-' + ListOfValues.get(ListOfValues.size()- 1);
            else
                a = ListOfValues.get(0);
            sch = '0 0 '+ Schdtime +' ? * '+ a;
    }

public string JobSchedular(){
string sch = GetCronStringForSchedule();
      string  jobID = system.schedule(BATCH_JOB_NAME, sch, batchjob);
return jobID;
}

Save this job ID some where so you can re use it in future if you want to abort this job from page.

Hope this helps you. Happy Coding !!