System Class

Contains methods for system operations, such as writing debug messages and scheduling jobs.

Namespace

System

System Methods

The following are methods for System. All methods are static.

abortJob(String)

Stops the specified job. The stopped job is still visible in the job queue in the Salesforce user interface.

Signature

public static Void abortJob(String Job_ID)

Parameters

Job_ID
Type: String
The Job_ID is the ID associated with either AsyncApexJob or CronTrigger.

Return Value

Type: Void

Usage

The following methods return the job ID that can be passed to abortJob.

assert(Boolean, Object)

Asserts that the specified condition is true. If it is not, a fatal error is returned that causes code execution to halt.

Signature

public static Void assert(Boolean condition, Object opt_msg)

Parameters

condition
Type: Boolean
opt_msg
Type: Object
(Optional) Custom message returned as part of the error message.

Return Value

Type: Void

Usage

You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.

assertEquals(Object, Object, Object)

Asserts that the first two arguments are the same. If they are not, a fatal error is returned that causes code execution to halt.

Signature

public static Void assertEquals(Object expected, Object actual, Object opt_msg)

Parameters

expected
Type: Object
Specifies the expected value.
actual
Type: Object
Specifies the actual value.
opt_msg
Type: Object
(Optional) Custom message returned as part of the error message.

Return Value

Type: Void

Usage

You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.

assertNotEquals(Object, Object, Object)

Asserts that the first two arguments are different. If they are the same, a fatal error is returned that causes code execution to halt.

Signature

public static Void assertNotEquals(Object expected, Object actual, Object opt_msg)

Parameters

expected
Type: Object
Specifies the expected value.
actual
Type: Object
Specifies the actual value.
opt_msg
Type: Object
(Optional) Custom message returned as part of the error message.

Return Value

Type: Void

Usage

You can’t catch an assertion failure using a try/catch block even though it is logged as an exception.

currentPageReference()

Returns a reference to the current page. This is used with Visualforce pages.

Signature

public static System.PageReference currentPageReference()

Return Value

Type: System.PageReference

Usage

For more information, see PageReference Class.

currentTimeMillis()

Returns the current time in milliseconds, which is expressed as the difference between the current time and midnight, January 1, 1970 UTC.

Signature

public static Long currentTimeMillis()

Return Value

Type: Long

debug(Object)

Writes the specified message, in string format, to the execution debug log. The DEBUG log level is used.

Signature

public static Void debug(Object msg)

Parameters

msg
Type: Object

Return Value

Type: Void

Usage

If the msg argument is not a string, the debug method calls String.valueOf to convert it into a string. The String.valueOf method calls the toString method on the argument, if available, or any overridden toString method if the argument is a user-defined type. Otherwise, if no toString method is available, it returns a string representation of the argument.

If the log level for Apex Code is set to DEBUG or higher, the message of this debug statement will be written to the debug log.

Note that when a map or set is printed, the output is sorted in key order and is surrounded with square brackets ([]). When an array or list is printed, the output is enclosed in parentheses (()).
Note
Calls to System.debug are not counted as part of Apex code coverage.Calls to System.debug are not counted as part of Apex code coverage.

For more information on log levels, see “Setting Debug Log Filters” in the Salesforce online help.

debug(LoggingLevel, Object)

Writes the specified message, in string format, to the execution debug log with the specified log level.

Signature

public static Void debug(LoggingLevel logLevel, Object msg)

Parameters

logLevel
Type: System.LoggingLevel
The logging level to set for this method.
msg
Type: Object
The message or object to write in string format to the execution debug log.

Return Value

Type: Void

Usage

If the msg argument is not a string, the debug method calls String.valueOf to convert it into a string. The String.valueOf method calls the toString method on the argument, if available, or any overridden toString method if the argument is a user-defined type. Otherwise, if no toString method is available, it returns a string representation of the argument.

Note
Calls to System.debug are not counted as part of Apex code coverage.

System Logging Levels

Use the loggingLevel enum to specify the logging level for the debug method.

Valid log levels are (listed from lowest to highest):
  • ERROR
  • WARN
  • INFO
  • DEBUG
  • FINE
  • FINER
  • FINEST

Log levels are cumulative. For example, if the lowest level, ERROR, is specified for Apex Code, only debug methods with the log level of ERROR are logged. If the next level, WARN, is specified, the debug log contains debug methods specified as either ERROR or WARN.

In the following example, the string MsgTxt is not written to the debug log because the log level is ERROR and the debug method has a level of INFO:

System.LoggingLevel level = LoggingLevel.ERROR;

System.debug(logginglevel.INFO, 'MsgTxt');

For more information on log levels, see “Setting Debug Log Filters” in the Salesforce online help.

equals(Object, Object)

Returns true if both arguments are equal. Otherwise, returns false.

Signature

public static Boolean equals(Object obj1, Object obj2)

Parameters

obj1
Type: Object
Object being compared.
obj2
Type: Object
Object to compare with the first argument.

Return Value

Type: Boolean

Usage

obj1 and obj2 can be of any type. They can be values, or object references, such as sObjects and user-defined types.

The comparison rules for System.equals are identical to the ones for the == operator. For example, string comparison is case insensitive. For information about the comparison rules, see the == operator.

getApplicationReadWriteMode()

Returns the read write mode set for an organization during Salesforce.com upgrades and downtimes.

Signature

public static System.ApplicationReadWriteMode getApplicationReadWriteMode()

Return Value

Type: System.ApplicationReadWriteMode

Valid values are:
  • DEFAULT
  • READ_ONLY

Usage

getApplicationReadWriteMode is available as part of 5 Minute Upgrade.

Using the System.ApplicationReadWriteMode Enum

Use the System.ApplicationReadWriteMode enum returned by the getApplicationReadWriteMode to programmatically determine if the application is in read-only mode during Salesforce upgrades and downtimes.

Valid values for the enum are:
  • DEFAULT
  • READ_ONLY
Example:
public class myClass {
  public static void execute() {
    ApplicationReadWriteMode mode = System.getApplicationReadWriteMode();

    if (mode == ApplicationReadWriteMode.READ_ONLY) {
      // Do nothing. If DML operaton is attempted in readonly mode, 
      // InvalidReadOnlyUserDmlException will be thrown. } else if (mode == ApplicationReadWriteMode.DEFAULT) { Account account = new Account(name = 'my account'); insert account; } } }

hashCode(Object)

Returns the hash code of the specified object.

Signature

public static Integer hashCode(Object obj)

Parameters

obj
Type: Object
The object to get the hash code for. This parameter can be of any type, including values or object references, such as sObjects or user-defined types.

Return Value

Type: Boolean

isBatch()

Returns true if the currently executing code is invoked by a batch Apex job; false otherwise.

Signature

public static Boolean isBatch()

Return Value

Type: Boolean

Usage

Since a future method can't be invoked from a batch Apex job, use this method to check if the currently executing code is a batch Apex job before you invoke a future method.

isFuture()

Returns true if the currently executing code is invoked by code contained in a method annotated with future; false otherwise.

Signature

public static Boolean isFuture()

Return Value

Type: Boolean

Usage

Since a future method can't be invoked from another future method, use this method to check if the current code is executing within the context of a future method before you invoke a future method.

isScheduled()

Returns true if the currently executing code is invoked by a scheduled Apex job; false otherwise.

Signature

public static Boolean isScheduled()

Return Value

Type: Boolean

now()

Returns the current date and time in the GMT time zone.

Signature

public static Datetime now()

Return Value

Type: Datetime

process(List<Ids>, String, String, String)

Processes the list of work item IDs.

Signature

public static List<Id> process(List<Id> WorkItemIDs, String Action, String Comments, String NextApprover)

Parameters

WorkItemIDs
Type: List<Id>
Action
Type: String
Comments
Type: String
NextApprover
Type: String

Return Value

Type: List<Id>

purgeOldAsyncJobs(Date)

Deletes asynchronous Apex job records for jobs that have finished execution before the specified date with a Completed, Aborted, or Failed status, and returns the number of records deleted.

Signature

public static Integer purgeOldAsyncJobs(Date dt)

Parameters

dt
Type: Date
Specifies the date up to which old records are deleted. The date comparison is based on the CompletedDate field of AsyncApexJob, which is in the GMT time zone.

Return Value

Type: Integer

Usage

Asynchronous Apex job records are records in AsyncApexJob.

The system cleans up asynchronous job records for jobs that have finished execution and are older than seven days. You can use this method to further reduce the size of AsyncApexJob by cleaning up more records.

Each execution of this method counts as a single row against the governor limit for DML statements.

Example

This example shows how to delete all job records for jobs that have finished before today’s date.
Integer count = System.purgeOldAsyncJobs
   (Date.today());
System.debug('Deleted ' + 
   count + ' old jobs.');

requestVersion()

Returns a two-part version that contains the major and minor version numbers of a package.

Signature

public static System.Version requestVersion()

Return Value

Type: System.Version

Usage

Using this method, you can determine the version of an installed instance of your package from which the calling code is referencing your package. Based on the version that the calling code has, you can customize the behavior of your package code.

The requestVersion method isn’t supported for unmanaged packages. If you call it from an unmanaged package, an exception will be thrown.

resetPassword(ID, Boolean)

Resets the password for the specified user.

Signature

public static System.ResetPasswordResult resetPassword(ID userID, Boolean send_user_email)

Parameters

userID
Type: ID
send_user_email
Type: Boolean

Return Value

Type: System.ResetPasswordResult

Usage

When the user logs in with the new password, they are prompted to enter a new password, and to select a security question and answer if they haven't already. If you specify true for send_user_email, the user is sent an email notifying them that their password was reset. A link to sign onto Salesforce using the new password is included in the email. Use setPassword(ID, String) if you don't want the user to be prompted to enter a new password when they log in.

Warning
Be careful with this method, and do not expose this functionality to end-users.

runAs(System.Version)

Changes the current package version to the package version specified in the argument.

Signature

public static Void runAs(System.Version version)

Parameters

version
Type: System.Version

Return Value

Type: Void

Usage

A package developer can use Version methods to continue to support existing behavior in classes and triggers in previous package versions while continuing to evolve the code. Apex classes and triggers are saved with the version settings for each installed managed package that the class or trigger references.

This method is used for testing your component behavior in different package versions that you upload to the AppExchange. This method effectively sets a two-part version consisting of major and minor numbers in a test method so that you can test the behavior for different package versions.

You can only use runAs in a test method. There is no limitation to the number of calls to this method in a transaction. For sample usage of this method, see Testing Behavior in Package Versions.

runAs(User)

Changes the current user to the specified user.

Signature

public static Void runAs(User user_var)

Parameters

user_var
Type: User

Return Value

Type: Void

Usage

All of the specified user's record sharing is enforced during the execution of runAs. You can only use runAs in a test method. For more information, see Using the runAs Method.

Note
The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

The runAs method implicitly inserts the user that is passed in as parameter if the user has been instantiated, but not inserted yet.

You can also use runAs to perform mixed DML operations in your test by enclosing the DML operations within the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations.

Note
Every call to runAs counts against the total number of DML statements issued in the process.

schedule(String, String, Object)

Use schedule with an Apex class that implements the Schedulable interface to schedule the class to run at the time specified by a Cron expression.

Signature

public static String schedule(String JobName, String CronExpression, Object schedulable_class)

Parameters

JobName
Type: String
CronExpression
Type: String
schedulable_class
Type: Object

Return Value

Type: String

Returns the scheduled job ID (CronTrigger ID).

Usage

Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time. Use the abortJob method to stop the job after it has been scheduled.

Note
Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

Using the System.Schedule Method

After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
Note
Use extreme care if you’re planning to schedule a class from a trigger. You must be able to guarantee that the trigger won’t add more scheduled classes than the 100 that are allowed. In particular, consider API bulk updates, import wizards, mass record changes through the user interface, and all cases where more than one record can be updated at a time.
The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class. This expression has the following syntax:
Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
Note
Salesforce schedules the class for execution at the specified time. Actual execution may be delayed based on service availability.

The System.Schedule method uses the user's timezone for the basis of all schedules.

The following are the values for the expression:

Name Values Special Characters
Seconds 0–59 None
Minutes 0–59 None
Hours 0–23 , - * /
Day_of_month 1–31 , - * ? / L W
Month 1–12 or the following:
  • JAN
  • FEB
  • MAR
  • APR
  • MAY
  • JUN
  • JUL
  • AUG
  • SEP
  • OCT
  • NOV
  • DEC
, - * /
Day_of_week 1–7 or the following:
  • SUN
  • MON
  • TUE
  • WED
  • THU
  • FRI
  • SAT
, - * ? / L #
optional_year null or 1970–2099 , - * /
The special characters are defined as follows:
Special CharacterDescription
,Delimits values. For example, use JAN, MAR, APR to specify more than one month.
-Specifies a range. For example, use JAN-MAR to specify more than one month.
*Specifies all values. For example, if Month is specified as *, the job is scheduled for every month.
?Specifies no specific value. This is only available for Day_of_month and Day_of_week, and is generally used when specifying a value for one and not the other.
/ Specifies increments. The number before the slash specifies when the intervals will begin, and the number after the slash is the interval amount. For example, if you specify 1/5 for Day_of_month, the Apex class runs every fifth day of the month, starting on the first of the month.
L Specifies the end of a range (last). This is only available for Day_of_month and Day_of_week. When used with Day of month, L always means the last day of the month, such as January 31, February 28 for leap years, and so on. When used with Day_of_week by itself, it always means 7 or SAT. When used with a Day_of_week value, it means the last of that type of day in the month. For example, if you specify 2L, you are specifying the last Monday of the month. Do not use a range of values with L as the results might be unexpected.
W Specifies the nearest weekday (Monday-Friday) of the given day. This is only available for Day_of_month. For example, if you specify 20W, and the 20th is a Saturday, the class runs on the 19th. If you specify 1W, and the first is a Saturday, the class does not run in the previous month, but on the third, which is the following Monday.
Tip
Use the L and W together to specify the last weekday of the month.
# Specifies the nth day of the month, in the format weekday#day_of_month. This is only available for Day_of_week. The number before the # specifies weekday (SUN-SAT). The number after the # specifies the day of the month. For example, specifying 2#2 means the class runs on the second Monday of every month.

The following are some examples of how to use the expression.

Expression Description
0 0 13 * * ? Class runs every day at 1 PM.
0 0 22 ? * 6L Class runs the last Friday of every month at 10 PM.
0 0 10 ? * MON-FRI Class runs Monday through Friday at 10 AM.
0 0 20 * * ? 2010 Class runs every day at 8 PM during the year 2010.

In the following example, the class proschedule implements the Schedulable interface. The class is scheduled to run at 8 AM, on the 13th of February.

proschedule p = new proschedule();
        String sch = '0 0 8 13 2 ?';
        system.schedule('One Time Pro', sch, p);

scheduleBatch(Database.Batchable, String, Integer)

Schedules a batch job to run once in the future after the specified time interval and with the specified job name.

Signature

public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer minutesFromNow)

Parameters

batchable
Type: Database.Batchable
An instance of a class that implements the Database.Batchable interface.
jobName
Type: String
The name if the job that this method will start.
minutesFromNow
Type: Integer
The time interval in minutes after which the job should start executing. This argument must be greater than zero.

Return Value

Type: String

The scheduled job ID (CronTrigger ID).

Usage

Note
Some things to note about System.scheduleBatch:
  • When you call System.scheduleBatch, Salesforce schedules the job for execution at the specified time. Actual execution might be delayed based on service availability.
  • The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
  • All scheduled Apex limits apply for batch jobs scheduled using System.scheduleBatch. After the batch job starts executing, all batch job limits apply and the job no longer counts toward scheduled Apex limits.
  • After calling this method and before the batch job starts, you can use the returned scheduled job ID to abort the scheduled job using the System.abortJob method.

For an example, see Using the System.scheduleBatch Method.

scheduleBatch(Database.Batchable, String, Integer, Integer)

Schedules a batch job to run once in the future after the specified the time interval, with the specified job name and scope size. Returns the scheduled job ID (CronTrigger ID).

Signature

public static String scheduleBatch(Database.Batchable batchable, String jobName, Integer minutesFromNow, Integer scopeSize)

Parameters

batchable
Type: Database.Batchable
The batch class that implements the Database.Batchable interface.
jobName
Type: String
The name of the job that this method will start.
minutesFromNow
Type: Integer
The time interval in minutes after which the job should start executing.
scopeSize
Type: Integer
The number of records that should be passed to the batch execute method.

Return Value

Type: String

Usage

Note
Some things to note about System.scheduleBatch:
  • When you call System.scheduleBatch, Salesforce schedules the job for execution at the specified time. Actual execution might be delayed based on service availability.
  • The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.
  • All scheduled Apex limits apply for batch jobs scheduled using System.scheduleBatch. After the batch job starts executing, all batch job limits apply and the job no longer counts toward scheduled Apex limits.
  • After calling this method and before the batch job starts, you can use the returned scheduled job ID to abort the scheduled job using the System.abortJob method.

For an example, see Using the System.scheduleBatch Method.

setPassword(ID, String)

Sets the password for the specified user.

Signature

public static Void setPassword(ID userID, String password)

Parameters

userID
Type: ID
password
Type: String

Return Value

Type: Void

Usage

When the user logs in with this password, they are not prompted to create a new password. Use resetPassword(ID, Boolean) if you want the user to go through the reset process and create their own password.

Warning
Be careful with this method, and do not expose this functionality to end-users.

submit(List<ID>, String, String)

Submits the processed approvals.

Signature

public static List<ID> submit(List<ID> workItemIDs, String Comments, String NextApprover)

Parameters

workItemIDs
Type: List<ID>
Comments
Type: String
NextApprover
Type: String

Return Value

Type: List<ID>

today()

Returns the current date in the current user's time zone.

Signature

public static Date today()

Return Value

Type: Date

© Copyright 2000–2014 salesforce.com, inc. All rights reserved.
Various trademarks held by their respective owners.