Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (5) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Scheduling an Apex Call From the Command Line

Scheduling an Apex Call From the Command Line

Post by Olivier_Nepomiachty  (2011-06-20)

Status: Unverified
Level: advanced


You want to execute an Apex method or an Apex batch from the command line, regardless of platform, using Perl and cURL. You may want to do this because:
  • Customer IT rules compliance: all the scheduled batches should be centralized.
  • Integration: a customer needs to execute an Apex batch (e.g. after a daily data load.)
  • Customer IT does not have resources with the required skills to write and maintain an application that will deal with Web Service APIs.

Solution big picture

This is a very simple solution that might be easily integrated in a shell script. The advantages are: no sweat for customer IT and the new capability of launching heavy processes running on the side.

Technical solution in a nutshell

A shell script calls a cURL command that deals with the API. cURL posts a SOAP login message to and opens a session. Then, cURL calls your Apex method exposed as a web service.

The use case we will walk through

Let's assume that your customer has a nightly batch that imports new leads (with an ETL for example), but the phone numbers format does not meet his CTI requirements, and so the system cannot match the inbound calls. We need to apply a filter on the phone numbers. The process stands in a simple string replacement using a regular expression: we will suppress all the none numerical characters with the pattern [^\d]*.

Solution deep dive

Why Perl?

Why Perl rather than Ruby or PHP? Well, Perl is a popular interpreted script language that is usually preinstalled on any Unix/Linux systems. Perl provides powerful text processing facilities without the arbitrary data length limits, facilitating easy manipulation of text files. (see )

Which Perl for your system?

Why cURL?

cURL is open source and stands for "Client for URLs". It is a command line tool for transferring data with URL syntax, supporting HTTP, HTTPS, FTP, SMTP, LDAP, etc. cURL handles cookies, HTTP headers, forms, all you need to mimic an internet browser. cURL main site, cURL download page.
  • Unix/Linux: build cURL from the sources (compile with openssl), download a package for your distribution (or use apt-get)
  • Windows: Get a version that support the HTTPS protocol

In action

The Perl script performs the following actions:
  • sends a login SOAP call to
  • parses the response and get the session id
  • sends a SOAP call that will execute the Apex command

We're assuming you have a Lead object in your org, and you've added a custom field:

  • Name: phone cti
  • API Name: phone_cti__c
  • type: text(50)
  • Read: all profiles
  • Write: only the System Administrator

Apex Batch

This batch makes a copy of the Lead phone field to the phone_cti__c field and applies a filter that removes all the none numeric characters. This is just some dummy code written for this recipe and not a CTI best practice! Here is the Apex code, test method is nested in the class:
BatchLeadPhones Blp = new BatchLeadPhones();
ID batchprocessid = Database.executeBatch(Blp);
global class BatchLeadPhones implements Database.Batchable<sObject>{
    public String query;
    global database.querylocator start(Database.BatchableContext BC){
        if ((query==null) || (query=='')) query='Select phone_cti__c From Lead';
        return Database.getQueryLocator(query);

    global void execute(Database.BatchableContext BC, List<sObject> scope){
        List<Lead> Leads = new List<Lead>();
        for(sObject s : scope){
                Lead l = (Lead)s;
                String ph = l.phone_cti__c.replaceAll('[^\\d]*','');
                if (ph != l.phone_cti__c) {
                    l.phone_cti__c = ph;
        if (Leads.Size()>0) update Leads; 
    global void finish(Database.BatchableContext BC){
    // test method
    static testMethod void test_BatchLeadPhones() {
        Lead l = new lead(LastName='lead test 123', phone_cti__c='+1 (555)123-4567', company='test company 456');
        insert l;
        BatchLeadPhones Blp = new BatchLeadPhones();
        Blp.query = 'Select phone_cti__c From lead Where ID=\''+l.Id+'\'';
        ID batchprocessid = Database.executeBatch(Blp);

Calling the Batch from the System Log window, run on all leads:
BatchLeadPhones Blp = new BatchLeadPhones();
ID batchprocessid = Database.executeBatch(Blp);
Run on a single lead:
BatchLeadPhones Blp = new BatchLeadPhones();
Blp.query = 'Select phone, phone_cti__c From lead Where ID=\'00QA000000GCVof\'';
ID batchprocessid = Database.executeBatch(Blp);
Calling the Batch from a web service: This is the Apex class exposed as a webservice:
global class callBatches {
    WebService static String CallBatchLeadPhones() {
        BatchLeadPhones Blp = new BatchLeadPhones();
        ID batchprocessid = Database.executeBatch(Blp);
        return batchprocessid;

    // Test Method
    TestMethod static void test_CallBatchLeadPhones() {
        Lead l = new lead(LastName='lead test 123', phone_cti__c='+1 (555)123-4567', company='test company 456');
        insert l;
        String ID = callBatches.CallBatchLeadPhones();
        System.assert(ID != null);

Now you need the WSDL file.

Go to Setup | App Setup | Develop | Apex Classes. On the row of the class callBatches, click on the link "WSDL" to download the WSDL. This XML file describes how to call the web service.

As I guess you are not fluent in WSDL, I recommend that you install SOAPUI on your system. SOAPUI is available as a free edition for gnu/Linux, Windows and Mac OS X; binary and source code. This recipe is not a SOAPUI tutorial; I will assume that you are familiar with this fantastic tool. You might want to provide a partner WSDL to SOAPUI and get the SOAP message to open a session in Here is the body:

<?xml version="1.0" encoding="utf-8" ?>
<env:Envelope xmlns:xsd="" xmlns:xsi="" xmlns:env="">
<n1:login xmlns:n1="">
Replace the username, password and token by your own credentials. will return a SOAP message containing informations regarding the user settings and the organization. The session id appears here:
Try this call using cURL. Open a shell:
curl --insecure --silent -H "Content-Type: text/xml;charset=UTF-8" -H "SOAPAction: login" -d @login.xml > loginresponse.xml
The SOAP response is saved to loginresponse.xml.

Remark: the --insecure parameter tells cURL not to check the peer. By default, cURL is always checking. See this page to understand how to work with certificates:

Create a new SOAPUI project with your Apex class WSDL, fill the "?" parameters. The set of values is documented in the WSDL file.

The SOAP message should look like:
<soapenv:Envelope xmlns:soapenv="" xmlns:cal="">
         <!--Zero or more repetitions:-->
</soapenv:Envelope> will answer:
<soapenv:Envelope xmlns:soapenv="" xmlns="">
         <debugLog>21.0 APEX_CODE,DEBUG

Solution Perl Script

The Perl script is making the same actions.
  • login call (login.xml)
  • get the session id
  • insert the session id in the Apex method web service call
  • call the Apex method (request1_tpl.xml)
request1_tpl.xml is a template SOAP call. The session Id is represented by:

Perl is replacing #ID# by the value of the session ID and saves the file to request1.xml.

Remember to update the instance name on line 16 (na1, na2, eu1, etc.)

#!/usr/bin/perl -w
use strict;

system('> loginresponse.xml');
system('curl --insecure --silent -H "Content-Type: text/xml;charset=UTF-8" -H "SOAPAction: login" -d @login.xml > loginresponse.xml');
open (FILE, 'loginresponse.xml') or die ('cannot read loginresponse.xml');
my $xml=''; while(<FILE>) { $xml.=$_; } close FILE;
if ($xml=~m|<sessionId>([0-9a-z!_\.-]+)</sessionId>|i) {
	my $sessionid=$1;
	open (FILER, 'request1_tpl.xml') or die ('cannot read request1_tpl.xml');
	$xml=''; while(<FILER>) { $xml.=$_; } close FILER;
	open (FILEW, '> request1.xml') or die ('cannot write to request1.xml');
	print FILEW $xml;
	close FILEW;
	system('curl --insecure --silent -H "Content-Type: text/xml;charset=UTF-8" -H "SOAPAction: SessionHeader" -d @request1.xml > response1.xml');

Remark: the command "system('> loginresponse.xml');" is not working on a Windows system. Replace it by "system('echo . 2> loginresponse.xml');"

That's it - command line invocation of web services using Perl and cURL.


This code isn't very pretty - especially having to handle the SOAP parsing. now supports OAuth, and using that to establish an authenticated session (via the username/password flow). The REST API might also help pretty up the code!

Resource files:



Recipe Activity - Please Log in to write a comment

Be the first to comment.


Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.