See also: What fields determine what is displayed in Open Activities vs. Activity History
For Task
records, you can write a trigger that compares the old and new value of IsClosed
.
trigger Task on Task (before update)
{
// handler, service, etc omitted for brevity
for (Task record : trigger.new)
{
Task oldRecord = trigger.oldMap.get(record.Id);
if (record.IsClosed && !oldRecord.IsClosed)
{
// do stuff
}
}
}
For Event
records, you will need a scheduled job in which you look for records whose StartDateTime
is less than Datetime.now()
, but also greater than the last time the job was run. There are a variety of ways to do that. The simplest may be to run the job daily and look for records which started yesterday, but you could also use a Hierarchy Custom Setting
or query for the last time the job was run. I'm sure there are other approaches which would work as well. If you run it daily, that would look something like:
public class MyEventJob implements Scheduleable
{
public void execute(ScheduleableContext context)
{
for (Event record : [
SELECT Id FROM Event
WHERE StartDateTime = YESTERDAY
]){
// do stuff
}
}
}