f.koglu
f.koglu

Reputation: 145

How can I make dynamic parameter of @Scheduled annotation?

I have a scheduled job and I want to get fixedRate dynamically but couldn't solve how to do it.

FixedRate gets value as milliseconds but I want to give time as hours. And I also tried read parameter from property file and multiply it but I did not work. How can I make this?

package com.ipera.communicationsuite.scheduleds;

import com.ipera.communicationsuite.models.FreeDbSize;
import com.ipera.communicationsuite.repositories.interfaces.IFreeDbSizeRepository;
import com.ipera.communicationsuite.repositories.interfaces.settings.IPropertiesRepository;
import com.ipera.communicationsuite.utilities.mail.SMTPConnection;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
@AllArgsConstructor
@PropertySource("classpath:scheduled.properties")
public class KeepAlive {
    private static Logger logger = LoggerFactory.getLogger(KeepAlive.class);

    private IFreeDbSizeRepository freeDbSizeRepository;
    private SMTPConnection smtpConnection;
    private IPropertiesRepository propertiesRepository;



    @Scheduled(fixedRateString ="${keepAlive.timer}")
    public void keepAliveMailSender() {
        StringBuilder content = new StringBuilder();
        ArrayList<File> files = getDrivers();
        List<FreeDbSize> list = freeDbSizeRepository.getFreeDbSize();
        FreeDbSize dbDiskInfo = freeDbSizeRepository.dbDiskSize();
        content.append("DB file size is: ").append(list.get(0).getType().equals("mdf") ? list.get(0).getFileSize() : list.get(1).getFileSize()).append(" MB\n")
                .append("DB log size is: ").append(list.get(0).getType().equals("ldf") ? list.get(0).getFileSize() : list.get(1).getFileSize()).append(" MB\n");
        propertiesRepository.updateByKey("DatabaseSize", list.get(0).getType().equals("mdf") ? list.get(0).getFileSize().toString() : list.get(1).getFileSize().toString());
        propertiesRepository.updateByKey("DatabaseLogSize", list.get(0).getType().equals("ldf") ? list.get(0).getFileSize().toString() : list.get(1).getFileSize().toString());
        propertiesRepository.updateByKey("FreeDiskSpaceForDb", dbDiskInfo.getFreeSpace().toString());
        for (int i = 0; i < files.size(); i++) {
            content.append("Free size for driver ").append(files.get(i)).append(" is ").append(files.get(i).getFreeSpace() / (1024 * 1024)).append(" MB\n");
            propertiesRepository.createIfNotExistOrUpdate(("FreeSpaceInDisk".concat(Character.toString(files.get(i).toString().charAt(0)))), Long.toString(files.get(i).getFreeSpace() / (1024 * 1024)));
        }
        if (dbDiskInfo.getName().equals("-1")) {
            content.append("This application has not permission to run query for calculate free size of disk.");
        } else {
            content.append("Free size of disk which contains Db is: ").append(dbDiskInfo.getFreeSpace());
        }
        smtpConnection.sendMail(content.toString(), "Server Is Up!!!", "[email protected]", "", "", "", "");
        logger.info("KeepAlive has runned.");

    }


    public ArrayList<File> getDrivers() {
        ArrayList<File> list = new ArrayList<>();

        File[] drives = File.listRoots();
        if (drives != null && drives.length > 0) {
            for (File aDrive : drives) {
                list.add(aDrive);
            }

        }
        return list;
    }
}

And also my propery file is here:

keepAlive.timer=86400000

Upvotes: 1

Views: 1746

Answers (1)

pirho
pirho

Reputation: 12245

You could use SpEL in your annotation like:

@Scheduled(fixedRateString ="#{new Long('${keepAlive.timer}') * 1000 * 3600}")

to have expression evaluated. So keepAlive.timer would be the amount of hours.

But in my opinion it would be an ugly solution. I would rather put it in the properties as you have it now and just add a comment like:

# 24 hours is: 1000 * 3600 * 24  
keepAlive.timer=86400000

Another way to use hours would be to use attribute cron that gives you more flexibility but might need some study before using:

In your code:

@Scheduled(cron = "${keepAlive.timer}")

and the cron expression in your properties - for example - like:

keepAlive.timer="*/60 00 21 * * ?"

This would run every day @ 21.00

Note this "*/60" it should accept also "0" here but in my case it did not

Upvotes: 1

Related Questions