function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Erica CoxErica Cox 

Scheduled task creation works once, fails nightly with 'cannot specify IDin an insert' error

This scheduled job works when scheduled singly, but when scheduled nightly causes an exception: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id].  The insert is outside of the for loop, which is what would ordinarily cause that exception.
global class QuarterlyReminderLogic implements Schedulable
{
    // This class will be scheduled to run daily. Use this string in the anon apex call
    // String CRON_EXP = '0 0 0 * * ?';
    private List<Task> newTasks = new List<Task>();
    
    // The execute function of the class is what will be invoked daily
    global void execute(SchedulableContext SC)
    {          
        List<Individual__c> inds = [SELECT Id, First_Name__c, Last_Name__c, 
                                  Assigned_User__c, Last_Quarterly_Visit__c, 
                                  Days_Since_Last_Qrtly_Visit__c
                                  FROM Individual__c WHERE  Last_Quarterly_Visit__c != null
                              		And Days_Since_Last_Qrtly_Visit__c in (60, 76, 83)];
        for(Individual__c ind : inds)
        {
            // 7 days out
            if (ind.Days_Since_Last_Qrtly_Visit__c == 83) {
				processTask(ind, 7);                                
            // 14 days out
            } else if (ind.Days_Since_Last_Qrtly_Visit__c == 76) {
                processTask(ind, 14);
            // 30 days out
            } else if (ind.Days_Since_Last_Qrtly_Visit__c == 60) {
                processTask(ind, 30);
            }
			
        }
        if (newTasks.size() > 0) {
            insert newTasks;
        }
    }
    
    // Give assigned User a new Task
    public void processTask(Individual__c ind, Integer days)
    {
        Task t = new Task();
        String t_description = 'Test task.'; 
        t.Description = t_description;
        t.OwnerId = ind.Assigned_User__c;  
        if (days == 30 || days == 14) {
            t.Priority = 'Normal';
        } else if (days == 7) {
            t.Priority = 'High';
            sendPmEmail(ind);
        }
        String subject_line = 'Quarterly activity due';
        t.Subject = subject_line;
        t.WhatId = ind.Id;
        t.ActivityDate = date.today();
        System.debug('Inserting task: '+t);
        newTasks.add(t);
    }
         
}