Alfresco: Scheduled Jobs

Note: @tommoz has pointed out to me a blog post that I’d never seen before from @Ixxus which is a complete example of writing a scheduled job (spring beans and all). You should really check out their excellent example if you need a full example of writing scheduled jobs for Alfresco.

One of the things that is easy to forget when adding/writing a new scheduled jobs is to wrap your code in a RetryingTransactionHelper _and_ a RunAs. When executing the scheduled job we need to make sure that we provide a transaction in which to perform your custom code and a user to perform the code under.

Example:

public void execute()
    {
        AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<Object>()
        {
            @Override
            public Object doWork()
                throws Exception
            {
                RetryingTransactionCallback<;Object>; txnWork = new RetryingTransactionCallback<Object>()
                {
                    public Object execute()
                        throws Exception
                    {
                        //Add logic here
                        return null;
                    }
                };

                transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false);
                return null;
            }
        }, user_authority);

    }

Hopefully this template will prove usefully to anyone writing a custom scheduled actions.