Getting error in Scheduling method in Cumulocity

I am developing a microservice, in which I want to schedule a method to call every 5 sec but I am getting the following error while doing it

language: Java
c8y-backend version: 1020.73.0

Service class:

public class FluentService {
    
    @Autowired
    private TenantOptionApi tenantOptionApi;
@Scheduled(fixedDelay = 5000)
    public void pollTenantOptions(){
        OptionPK optionPK = new OptionPK();
       optionPK.setCategory(AuthenticationConstants.TENANT_OPTION_CATEGORY);
        optionPK.setKey("data-mapping");
        OptionRepresentation optionRepresentation
tenantOptionApi.getOption(optionPK);
        String jsonString = optionRepresentation.getValue();
        System.out.println(jsonString);
        DataMapping dataMapping = JSONParser.defaultJSONParser().parse(DataMapping.class,jsonString);
        System.out.println(dataMapping.toString());
    }

Error message i am getting:

org.springframework.beans.factory.support.ScopeNotActiveException: Error creating bean with name 'scopedTarget.tenantOptionApi': Scope 'tenant' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: Not within any context!

Can you try:

public class FluentService {

    @Autowired
    private TenantOptionApi tenantOptionApi;

    @Autowired
    private MicroserviceSubscriptionsService subscriptionsService;

    @Scheduled(fixedDelay = 5000)
    public void pollTenantOptions() {
        subscriptionService.runForTenant("your-tenant-id", () - > {
            OptionPK optionPK = new OptionPK();
            optionPK.setCategory(AuthenticationConstants.TENANT_OPTION_CATEGORY);
            optionPK.setKey("data-mapping");
            OptionRepresentation optionRepresentation
            tenantOptionApi.getOption(optionPK);
            String jsonString = optionRepresentation.getValue();
            System.out.println(jsonString);
            DataMapping dataMapping = JSONParser.defaultJSONParser().parse(DataMapping.class, jsonString);
            System.out.println(dataMapping.toString());
        });
    }
}

I’ve wrapped your code around the MicroserviceSubscriptionsService , this should give your code the tenant scope.

See also: Microservice Client that connect to multiple devices - #2 by Kai_Sieben

2 Likes

As an additional remark to Korbinian’s answer. Instead of hardcoding your tenant id you can also read the tenant from the environment variables, if you only need the tenant id of the tenant on which the Microservice is deployed.

import org.springframework.beans.factory.annotation.Value;

@Value("${C8Y.bootstrap.tenant}")
String bootstrapTenant;

In case you want to run the scheduler in a MULTI_TENANT scenario, you can execute it per tenant using subscriptionService.runForEachTenant()



Christian Guether

2 Likes