<commit_before>// Copyright 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.ioc.internal.services.cron;

import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.services.ParallelExecutor;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.apache.tapestry5.ioc.services.RegistryShutdownListener;
import org.apache.tapestry5.ioc.services.cron.PeriodicExecutor;
import org.apache.tapestry5.ioc.services.cron.PeriodicJob;
import org.apache.tapestry5.ioc.services.cron.Schedule;
import org.slf4j.Logger;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PeriodicExecutorImpl implements PeriodicExecutor, Runnable, RegistryShutdownListener
{
    private final ParallelExecutor parallelExecutor;

    private final Logger logger;

    // Synchronized by this
    private final List<Job> jobs = CollectionFactory.newList();

    private final Thread thread = new Thread(this, "Tapestry PeriodicExecutor");

    // Synchronized by this. Set when the registry is shutdown.
    private boolean shutdown;

    private static final long FIVE_MINUTES = 5 * 60 * 1000;

    private final AtomicInteger jobIdAllocator = new AtomicInteger();

    private class Job implements PeriodicJob, Invokable<Void>
    {
        final int jobId = jobIdAllocator.incrementAndGet();

        private final Schedule schedule;

        private final String name;

        private final Runnable runnableJob;

        private boolean executing, canceled;

        private long nextExecution;

        public Job(Schedule schedule, String name, Runnable runnableJob)
        {
            this.schedule = schedule;
            this.name = name;
            this.runnableJob = runnableJob;

            nextExecution = schedule.firstExecution();
        }

        public String getName()
        {
            return name;
        }

        public synchronized long getNextExecution()
        {
            return nextExecution;
        }


        public synchronized boolean isExecuting()
        {
            return executing;
        }

        public synchronized boolean isCanceled()
        {
            return canceled;
        }

        public synchronized void cancel()
        {
            canceled = true;

            if (!executing)
            {
                removeJob(this);
            }

            // Otherwise, it will be caught when the job finishes execution.
        }

        @Override
        public synchronized String toString()
        {
            StringBuilder builder = new StringBuilder("PeriodicJob[#").append(jobId);


            builder.append(", (").append(name).append(")");

            if (executing)
            {
                builder.append(", executing");
            }

            if (canceled)
            {
                builder.append(", canceled");
            } else
            {
                builder.append(String.format(", next execution %Tk:%<TM:%<TS+%<TL", nextExecution));
            }

            return builder.append("]").toString();
        }

        /**
         * Starts execution of the job; this sets the executing flag, calculates the next execution time,
         * and uses the ParallelExecutor to run the job.
         */
        synchronized void start()
        {
            executing = true;

            // This is a bit naive; it assumes there will not be a delay waiting to execute. There's a lot of options
            // here, such as basing the next execution on the actual start time, or event actual completion time, or allowing
            // overlapping executions of the Job on a more rigid schedule.  Use Quartz.

            nextExecution = schedule.nextExecution(System.currentTimeMillis());

            parallelExecutor.invoke(this);

            if (logger.isTraceEnabled())
            {
                logger.trace(this + " sent for execution");
            }
        }

        synchronized void cleanupAfterExecution()
        {
            if (logger.isTraceEnabled())<commit_msg>Passing the previous execution's time to Schedule#nextExecution instead of current millis.<commit_after>// Copyright 2011 The Apache Software Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.ioc.internal.services.cron;

import org.apache.tapestry5.ioc.Invokable;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import org.apache.tapestry5.ioc.internal.util.CollectionFactory;
import org.apache.tapestry5.ioc.services.ParallelExecutor;
import org.apache.tapestry5.ioc.services.RegistryShutdownHub;
import org.apache.tapestry5.ioc.services.RegistryShutdownListener;
import org.apache.tapestry5.ioc.services.cron.PeriodicExecutor;
import org.apache.tapestry5.ioc.services.cron.PeriodicJob;
import org.apache.tapestry5.ioc.services.cron.Schedule;
import org.slf4j.Logger;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PeriodicExecutorImpl implements PeriodicExecutor, Runnable, RegistryShutdownListener
{
    private final ParallelExecutor parallelExecutor;

    private final Logger logger;

    // Synchronized by this
    private final List<Job> jobs = CollectionFactory.newList();

    private final Thread thread = new Thread(this, "Tapestry PeriodicExecutor");

    // Synchronized by this. Set when the registry is shutdown.
    private boolean shutdown;

    private static final long FIVE_MINUTES = 5 * 60 * 1000;

    private final AtomicInteger jobIdAllocator = new AtomicInteger();

    private class Job implements PeriodicJob, Invokable<Void>
    {
        final int jobId = jobIdAllocator.incrementAndGet();

        private final Schedule schedule;

        private final String name;

        private final Runnable runnableJob;

        private boolean executing, canceled;

        private long nextExecution;

        public Job(Schedule schedule, String name, Runnable runnableJob)
        {
            this.schedule = schedule;
            this.name = name;
            this.runnableJob = runnableJob;

            nextExecution = schedule.firstExecution();
        }

        public String getName()
        {
            return name;
        }

        public synchronized long getNextExecution()
        {
            return nextExecution;
        }


        public synchronized boolean isExecuting()
        {
            return executing;
        }

        public synchronized boolean isCanceled()
        {
            return canceled;
        }

        public synchronized void cancel()
        {
            canceled = true;

            if (!executing)
            {
                removeJob(this);
            }

            // Otherwise, it will be caught when the job finishes execution.
        }

        @Override
        public synchronized String toString()
        {
            StringBuilder builder = new StringBuilder("PeriodicJob[#").append(jobId);


            builder.append(", (").append(name).append(")");

            if (executing)
            {
                builder.append(", executing");
            }

            if (canceled)
            {
                builder.append(", canceled");
            } else
            {
                builder.append(String.format(", next execution %Tk:%<TM:%<TS+%<TL", nextExecution));
            }

            return builder.append("]").toString();
        }

        /**
         * Starts execution of the job; this sets the executing flag, calculates the next execution time,
         * and uses the ParallelExecutor to run the job.
         */
        synchronized void start()
        {
            executing = true;

            // This is a bit naive; it assumes there will not be a delay waiting to execute. There's a lot of options
            // here, such as basing the next execution on the actual start time, or event actual completion time, or allowing
            // overlapping executions of the Job on a more rigid schedule.  Use Quartz.

            nextExecution = schedule.nextExecution(nextExecution);

            parallelExecutor.invoke(this);

            if (logger.isTraceEnabled())
            {
                logger.trace(this + " sent for execution");
            }
        }

        synchronized void cleanupAfterExecution()
        {
            if (logger.isTraceEnabled())
{'fraction_non_alphanumeric': 0.0813246698805282, 'fraction_numerical': 0.005449591280653951, 'mean_word_length': 2.267031838411503, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6546577', 'n_tokens_mistral': 2441, 'n_tokens_neox': 2326, 'n_words': 759}