new task.  Embedded state and create time will be initialized.
But this task still will have to be persisted with
TransactionContext
.getCurrent()
.getPersistenceSession()
.insert(task);
170353
public static TaskEntity create() {
    TaskEntity task = new TaskEntity();
    task.isIdentityLinksInitialized = true;
    task.setCreateTime(ClockUtil.getCurrentTime());
    return task;
  }
1094021
public static TaskAnnouncement create(Task task, TaskStatus status, TaskLocation location)
  {
    return create(task.getId(), task.getType(), task.getTaskResource(), status, location, task.getDataSource());
  }
568691
@Override
    public void create(TaskRecord taskRecord) throws Exception {
        Task task = new Task(taskRecord);
        EntityManager em = getPersistenceServiceUnit().createEntityManager();
        try {
            em.persist(task);
            em.flush();
            taskRecord.setId(task.ID);
        } finally {
            em.close();
        }
    }
110943
public static TaskEntity createAndInsert(VariableScope execution) {
    TaskEntity task = create();

    if (execution instanceof ExecutionEntity) {
      ExecutionEntity executionEntity = (ExecutionEntity) execution;
      task.setExecution(executionEntity);
      task.skipCustomListeners = executionEntity.isSkipCustomListeners();
      task.insert(executionEntity);
      return task;

    }
    else if (execution instanceof CaseExecutionEntity) {
      task.setCaseExecution((DelegateCaseExecution) execution);
    }

    task.insert(null);
    return task;
  }
564085
public void initialize() {

        if (m_taskFuture != null) {
            // in case initialize has been called before on this object, cancel the existing task
            m_taskFuture.cancel(false);
            m_taskFuture = null;
        }
        m_state = readCompleteConfiguration();
        // In debug mode, use a shorter delay to speed up the test cases
        long delay = DEBUG ? 500 : TASK_DELAY_MILLIS;
        m_taskFuture = OpenCms.getExecutor().scheduleWithFixedDelay(new Runnable() {

            public void run() {

                performUpdate();
            }
        }, delay, delay, TimeUnit.MILLISECONDS);
    }
807440
@GuardedBy("evictionLock")
    void runTasksInChain(Task task) {
        while (task != null) {
            Task current = task;
            task = task.getNext();
            current.setNext(null);
            current.run();
        }
    }
1221135
public void createLoadTasksPerBusinessDate(CacheLoaderContext context, Object sourceAttribute, BooleanFilter postLoadFilter)
    {
        if (context.getRefreshInterval() != null)
        {
            this.createLoadTasksForRefresh(context, sourceAttribute, postLoadFilter);
        }
        else
        {
            this.createLoadTasksForInitialLoad(context, sourceAttribute, postLoadFilter);
        }
    }
1190000
@Override
	public CompletableFuture<Acknowledge> updateTaskExecutionState(
			final TaskExecutionState taskExecutionState) {
		checkNotNull(taskExecutionState, "taskExecutionState");

		if (executionGraph.updateState(taskExecutionState)) {
			return CompletableFuture.completedFuture(Acknowledge.get());
		} else {
			return FutureUtils.completedExceptionally(
				new ExecutionGraphException("The execution attempt " +
					taskExecutionState.getID() + " was not found."));
		}
	}
1109428
protected void init() {
        // create a synchronisation task which makes sure that the change requested by
        // the internal future has at one time been synchronized to the remote
        synchronisationFuture = GlobalCachedExecutorService.submit(() -> {
            dataProvider.addDataObserver(notifyChangeObserver);
            try {
                dataProvider.waitForData();
                T result = internalFuture.get();
                waitForSynchronization(result);
            } catch (CouldNotPerformException ex) {
                ExceptionPrinter.printHistory("Could not sync with internal future!", ex, logger);
            } finally {
                dataProvider.removeDataObserver(notifyChangeObserver);
            }
            return null;
        });
    }
861166
public <K, T extends Persistable<K>>
    K create(
                    final Class<T> type,
                    final T object
                    )
    {
        K  p_id = _executeTx( "create", type, object,
                        new TransactionCallback<K>()
                        {
                            public K doInTransaction( final TransactionStatus status )
                            {
                                return getDao( type ).create( object );
                            }
                        }
        );

        return p_id;
    }
164924
function addTaskToFluence(task, done) {
        if (done) {
            done = "1"
        } else {
            done = "0"
        }
        const query = `INSERT INTO ${todoTable} VALUES ('${task}', ${done})`;
        session.request(query).result().then((r) => {
            console.log("task inserted")
        })
    }
1036697
public void initialize() {

        if (m_taskFuture != null) {
            m_taskFuture.cancel(false);
            m_taskFuture = null;
        }
        reload();
        m_taskFuture = OpenCms.getExecutor().scheduleWithFixedDelay(
            this::performUpdate,
            UPDATE_DELAY_MILLIS,
            UPDATE_DELAY_MILLIS,
            TimeUnit.MILLISECONDS);

    }
26919
@Override
  public void recordTaskCreated(TaskEntity task, ExecutionEntity execution) {
    if (isHistoryLevelAtLeast(HistoryLevel.AUDIT)) {
      HistoricTaskInstanceEntity historicTaskInstance = getHistoricTaskInstanceEntityManager().create(task, execution);
      getHistoricTaskInstanceEntityManager().insert(historicTaskInstance, false);
    }
    
    recordTaskId(task);
  }
316002
private void initialize(Function<SqlTask, ?> onDone, CounterStat failedTasks)
    {
        requireNonNull(onDone, "onDone is null");
        requireNonNull(failedTasks, "failedTasks is null");
        taskStateMachine.addStateChangeListener(new StateChangeListener<TaskState>()
        {
            @Override
            public void stateChanged(TaskState newState)
            {
                if (!newState.isDone()) {
                    return;
                }

                // Update failed tasks counter
                if (newState == FAILED) {
                    failedTasks.update(1);
                }

                // store final task info
                while (true) {
                    TaskHolder taskHolder = taskHolderReference.get();
                    if (taskHolder.isFinished()) {
                        // another concurrent worker already set the final state
                        return;
                    }

                    if (taskHolderReference.compareAndSet(taskHolder, new TaskHolder(createTaskInfo(taskHolder), taskHolder.getIoStats()))) {
                        break;
                    }
                }

                // make sure buffers are cleaned up
                if (newState == FAILED || newState == ABORTED) {
                    // don't close buffers for a failed query
                    // closed buffers signal to upstream tasks that everything finished cleanly
                    outputBuffer.fail();
                }
                else {
                    outputBuffer.destroy();
                }

                try {
                    onDone.apply(SqlTask.this);
                }
                catch (Exception e) {
                    log.warn(e, "Error running task cleanup callback %s", SqlTask.this.taskId);
                }
            }
        });
    }
411937
private void insertOrUpdateTasks(TaskStartEvent event) {
        Assignment old = event.getOldAssignment();
        Assignment current = event.getNewAssignment();

        Map<Integer, String> task2Component = event.getTask2Component();
        List<KVSerializable> taskTrackList = new ArrayList<>();

        // assign
        if (old == null) {
            Set<ResourceWorkerSlot> workers = current.getWorkers();
            logger.info("old workers are null, assigned workers:{}", Joiner.on(",").join(workers));
            for (ResourceWorkerSlot worker : workers) {
                Set<Integer> tasks = worker.getTasks();
                for (Integer task : tasks) {
                    TaskTrack track = new TaskTrack(
                            event.getClusterMetricsContext().getClusterName(), event.getTopologyId());
                    track.setStart(new Date(event.getTimestamp()));
                    track.setComponent(task2Component.get(task));
                    track.setHost(worker.getHostname());
                    track.setPort(worker.getPort());
                    track.setTaskId(task);

                    taskTrackList.add(track);
                }
            }
        } else { // rebalance, we only insert newly assigned tasks
            Set<ResourceWorkerSlot> oldWorkers = old.getWorkers();
            Joiner joiner = Joiner.on(",");
            logger.info("old workers:{}, new workers:{}", joiner.join(oldWorkers), joiner.join(current.getWorkers()));
            for (ResourceWorkerSlot worker : current.getWorkers()) {
                // a new worker, insert all tasks
                if (!oldWorkers.contains(worker)) {
                    for (Integer task : worker.getTasks()) {
                        TaskTrack track = new TaskTrack(
                                event.getClusterMetricsContext().getClusterName(),
                                event.getTopologyId());
                        track.setStart(new Date(event.getTimestamp()));
                        track.setComponent(task2Component.get(task));
                        track.setHost(worker.getHostname());
                        track.setPort(worker.getPort());
                        track.setTaskId(task);

                        taskTrackList.add(track);
                    }
                } else {
                    for (Integer task : worker.getTasks()) {
                        ResourceWorkerSlot oldWorker = old.getWorkerByTaskId(task);
                        if (oldWorker != null) {

                            // update end time of old task
                            TaskTrack oldTrack = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            oldTrack.setEnd(new Date(event.getTimestamp()));
                            oldTrack.setTaskId(task);
                            oldTrack.setHost(oldWorker.getHostname());
                            oldTrack.setPort(oldWorker.getPort());
                            taskTrackList.add(oldTrack);

                            // insert new task
                            TaskTrack track = new TaskTrack(
                                    event.getClusterMetricsContext().getClusterName(),
                                    event.getTopologyId());
                            track.setStart(new Date());
                            track.setComponent(task2Component.get(task));
                            track.setHost(worker.getHostname());
                            track.setPort(worker.getPort());
                            track.setTaskId(task);
                            taskTrackList.add(track);
                        }
                    }
                }
            }
        }
        if (taskTrackList.size() > 0) {
            batchAdd(taskTrackList, TABLE_TASK_TRACK);
        }
    }
737614
public void prepare(PersistentTransaction transaction) throws PersistenceException, SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "prepare", "Transaction="+transaction);

        // Defect 363755
        if (!_available)
        {
            MessageStoreUnavailableException msue = new MessageStoreUnavailableException("Operation not possible as MessageStore is unavailable!");
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Operation not possible as MessageStore is unavailable!");
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
            throw msue;
        }

        //Get the task list from the transaction
        TaskList taskList = (TaskList) transaction.getWorkList();

        PersistentTranId       xid = transaction.getPersistentTranId();
        TransactionState tranState = transaction.getTransactionState();
        int          numberOfTasks = taskList.countLinks();

        boolean requiresSyncPersistence = false;

        // Defect 530772
        boolean requiresSpillPersistence = false;

        // Defect 298584
        // Batching context will only be created if we
        // have synchronous work to do.
        BatchingContext syncBatch = null;
        List             syncList = null;

        if (taskList.hasStoreAlways() || taskList.hasStoreEventually() || taskList.hasStoreMaybe())
        {
            // We have synchronous work to do so
            // we need to build up a list of tasks.
            Iterator iterator = taskList.iterator();
            while (iterator.hasNext())
            {
                Operation          task = (Operation) iterator.next();
                Persistable persistable = task.getPersistable();

                // Defect 451518
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(this, tc, "Preparing Task: "+task);

                if (persistable != null && persistable.requiresPersistence())
                {
                    int     storageStrategy = persistable.getStorageStrategy();
                    TupleTypeEnum tupleType = persistable.getTupleType();

                    // Feature SIB0112i.ms.1
                    // We only need to persist our synchronous work at this point. If our
                    // transaction prepares successfully then at commit time we can make
                    // sure our STORE_MAYBE work is persisted.

                    // Defect 530772
                    // Are we a STORE_MAYBE Item? If so then we can be dispatched to the
                    // spill dispatcher. If not then we need to be persisted synchronously.
                    // This is to avoid adding complication to the spill dispatcher as it
                    // does not worry about the order in which things are persisted so an
                    // Item on a stream can be hardened to disk before the stream. This will
                    // not work in the filestore case.
                    if (tupleType != TupleTypeEnum.ITEM_STREAM &&
                        tupleType != TupleTypeEnum.REFERENCE_STREAM &&
                        storageStrategy == AbstractItem.STORE_MAYBE)
                    {
                        if (requiresSpillPersistence == false)
                        {
                            requiresSpillPersistence = true;
                        }
                    }
                    // If not we are synchronous.
                    else
                    {
                        // Defect 298584
                        // Only create our batching context once we know for sure
                        // that we have some synchronous work to do.
                        if (requiresSyncPersistence == false)
                        {
                            syncList  = new ArrayList(numberOfTasks);
                            syncBatch = new BatchingContextImpl(_objectManager, _permanentStore, transaction);
                            transaction.setBatchingContext(syncBatch);
                            requiresSyncPersistence = true;
                        }

                        //Associate the global tran id with the persistable
                        persistable.setPersistentTranId(xid);

                        task.persist(syncBatch, tranState);
                        syncList.add(persistable);
                    }
                }
            }
        }


        // Defect 530772
        // Check the health of the spill dispatcher to minimise the risk
        // of splitting a transaction.
        if (requiresSpillPersistence)
        {
            if (!_spillDispatcher.isHealthy())
            {
                // Defect 345250
                // The dispatcher is not currently accepting new work as it has
                // hit a problem. Details of the problem should have been output
                // to the logs by the dispatcher thread at the point where it
                // occurred.
                PersistenceException pe = new PersistenceException("SPILL_DISPATCHER_CANNOT_ACCEPT_WORK_SIMS1578");
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "The spill dispatcher cannot accept work!", pe);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
                throw pe;
            }
        }

        // Feature SIB0112i.ms.1
        // We only have to do some work in prepare if we have
        // synchronous work to add to the file store.
        if (requiresSyncPersistence)
        {
            try
            {
                // As this is a prepare we use the addIndoubtXid()
                // method to inform the batching context that we only
                // wish to prepare during this executeUpdate() call.
                syncBatch.addIndoubtXID(xid);

                // Submit the batch and trigger the prepare in the
                // object manager.
                syncBatch.executeBatch();

                // If we get to this point then the prepare was successful, so we need to
                // notify the cache layer
                Iterator iterator = syncList.iterator();
                while (iterator.hasNext())
                {
                    Tuple tuple = (Tuple)iterator.next();

                    // Both these methods need to be called to indicate to the cache
                    // that it can soften its in-memory reference to the persistable
                    tuple.persistableOperationBegun();
                    tuple.persistableOperationCompleted();
                }
            }
            catch (PersistenceException pe)
            {
                com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.PersistableMessageStoreImpl.prepare", "1:1615:1.81.1.6", this);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Exception caught preparing transaction in object store!", pe);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
                throw pe;
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "prepare");
    }
129171
function acquire(timeToLive, requestorId, task) {
  timeToLive    = timeToLive || DEFAULT_TIME_TO_LIVE;

  if(!requestorId) {
    throw new TypeError('RequestorIdNotPresent');
  }
  if(!task) {
    throw new TypeError('TaskNotFound');
  }
  if(isTaskLocked(task)) {
    if(isLockHolder(task, requestorId)) {

      task.semaphore.time  = timestamp();

      return task;
    }

    throw new LockError('TaskAlreadyLocked');
  }

  task.semaphore  = {
    key:          hashKey(requestorId, task.id),
    time:         timestamp(),
    ttl:          timeToLive
  };

  return task;
}