2

I have many services that run on a daily basis all based on cron values passed to them. I'm working on a service that needs to know the number of times per day each service does its job. Is it possible to convert a cron expression into a 'number per day/week' in Java 1.8 specifically? Just fyi, I'm in a spring boot project for this, in case that somehow makes any difference.

For example, assume I have an expression like 0 1 0-20/4 * * *. That job would run 5 times every day. I had something in mind like:

float dailyUploads = someLibrary.cronToFloat("0 1 0-20/4 * * *");

where dailyUploads == 5.0

When I google this, most results only deal with creating cron expressions. I did find one interesting post about converting cron to date-time values.

It occurs to me that I could use a cron sequence generator (mentioned in the above-linked answer) to sequence until the day changes followed by counting the results, but that only gives me the results for that one day; what about a service that runs once every year? I just can't find a clean way to do this.

Thank you for any assistance.

geekTechnique
  • 850
  • 1
  • 11
  • 38

2 Answers2

2

One approach is to use a library like http://cron-parser.com/. With that, you could have code that looks something like this:

import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.parser.CronParser;

import java.util.Locale;

import static com.cronutils.model.CronType.QUARTZ;

// ...

    final String expr = "0 * * 1-3 * ? *";
    
    CronDefinition cronDefinition =
            CronDefinitionBuilder.instanceDefinitionFor(QUARTZ);

    CronParser parser = new CronParser(cronDefinition);

    CronDescriptor descriptor = CronDescriptor.instance(Locale.UK);

    String description = descriptor.describe(parser.parse(expr));

The output from that would be the following:

every minute every day between 1 and 3
Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
1

cron-utils would work perfectly too

Ola Aronsson
  • 411
  • 4
  • 7