7

What does Salesforce use as the system time when running those jobs? The current system time (UTC)?

My context is that I have a job that is run every 30 minutes and it executes a task for some of my users. The User object has 4 numeric fields to represent start hour, end hour, start minute and end minute. With those fields I calculate the second in the day the job should start, and the second it should end. With those two values I can compare with the system's current second, and check if the job should run for the user or not.

Some days ago this was a scheduled class that was rescheduling itself using my user credentials ('Scheduled by Renato' and records would be marked as 'Last modified by Renato' too). Then I decided to change to platform events so they would be marked as "Last modified by Automated Process" instead (which is what I want).

Now everytime the class is run, it publishes a event, and the event trigger fires the class' code that was inside the execute block. However, the timing seems off, and users are not receiving the tasks in the correct time anymore.

To get the current second correctly, I've used this code:

Integer offset = TimeZone.getTimeZone('America/Sao_Paulo').getOffSet(DateTime.now());
Integer current_second = Util.getCurrentSecond() + (offset/1000);

Util class' method:

public static Integer getCurrentSecond() {
    return Integer.valueOf((DateTime.now().hour() * 60 * 60) + (DateTime.now().minute() * 60));
}

Have I not considered something when using the Platform Events?

Edit:

I just edited my code to include a call to a service that sends a message to me through Telegram. The code ran in the platform event context, and the timing is correct. System time is UTC and São Paulo is UTC-2 (originally -3, but -2 because of Daylight Saving Time):

System second: 21960
Current second: 14760
0

After searching for a while and after some debugging I managed to get the system to print its timezone using UserInfo.getTimeZone(). Salesforce server runs in the Pacific Standard Time (PST) timezone.

Now for the issue I was having: apparently there's a bug with the DateTime.now().hour() call. When I ran it at 11 AM (GMT-2) the system would print the DateTime as expected, as 13:00:00. However, when using .hour() Apex would return me 5 instead of 13. This caused a miscalculation in my code.

I've then fixed this temporarily with the following code:

Integer offset = TimeZone.getTimeZone('America/Sao_Paulo').getOffSet(DateTime.now());
String ds = DateTime.now()+''; // datetime string
Integer hour = Integer.valueOf(ds.split(' ')[1].split(':')[0]) + (offset/1000/60/60);

And .minute() and .second() are working just fine, by the way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.